要使用PHP操作MySQL數據庫,您需要遵循以下步驟:
mysqli
或PDO
擴展。以下是使用這兩種擴展的示例代碼:使用mysqli
擴展:
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 創建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
使用PDO
擴展:
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 設置 PDO 錯誤模式為異常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "連接失敗: " . $e->getMessage();
}
檢索數據(SELECT):
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 輸出數據
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 結果";
}
插入數據(INSERT):
$sql = "INSERT INTO your_table (name, age) VALUES ('John Doe', 30)";
if ($conn->query($sql) === TRUE) {
echo "新記錄插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
更新數據(UPDATE):
$sql = "UPDATE your_table SET name='Jane Doe' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "更新成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
刪除數據(DELETE):
$sql = "DELETE FROM your_table WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "刪除成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
使用mysqli
擴展關閉連接:
$conn->close();
使用PDO
擴展關閉連接:
$conn = null;
這就是使用PHP操作MySQL數據庫的基本方法。請根據您的需求調整代碼示例。