MySQL 是一個廣泛使用的開源關系型數據庫管理系統,下面我們就來了解一下如何使用 MySQL 進行數據庫操作。
// 建立連接 $conn = mysqli_connect("localhost", "username", "password", "database_name"); if (!$conn) { die("連接失敗: " . mysqli_connect_error()); } // 創建表 $sql = "CREATE TABLE Persons ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, age INT(3) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; if (mysqli_query($conn, $sql)) { echo "創建成功!"; } else { echo "創建失敗: " . mysqli_error($conn); } // 插入數據 $sql = "INSERT INTO Persons (name, age, email) VALUES ('張三', 20, 'zhangsan@example.com')"; if (mysqli_query($conn, $sql)) { echo "插入成功!"; } else { echo "插入失敗: " . mysqli_error($conn); } // 查詢數據 $sql = "SELECT id, name, age, email FROM Persons"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) >0) { while($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row["id"] . " Name: " . $row["name"] . " Age: " . $row["age"] . " Email: " . $row["email"] . "
"; } } else { echo "0 結果"; } // 更新數據 $sql = "UPDATE Persons SET age = 21 WHERE name = '張三'"; if (mysqli_query($conn, $sql)) { echo "更新成功!"; } else { echo "更新失敗: " . mysqli_error($conn); } // 刪除數據 $sql = "DELETE FROM Persons WHERE name = '張三'"; if (mysqli_query($conn, $sql)) { echo "刪除成功!"; } else { echo "刪除失敗: " . mysqli_error($conn); } // 關閉連接 mysqli_close($conn);
以上是 MySQL 數據庫的基本操作示例,開發者可以根據自己的需求進行修改和擴展。
下一篇mysql使用成本