要使用PHP操作MySQL數據庫,您需要遵循以下步驟:
使用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();
}
插入數據:
$sql = "INSERT INTO your_table (column1, column2) VALUES ('value1', 'value2')";
if ($conn->query($sql) === TRUE) {
echo "新記錄插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
查詢數據:
$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["column1"]. " - Value: " . $row["column2"]. "<br>";
}
} else {
echo "0 結果";
}
更新數據:
$sql = "UPDATE your_table SET column1 = 'new_value1' WHERE id = 1";
if ($conn->query($sql) === TRUE) {
echo "更新成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
刪除數據:
$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數據庫的基本方法。請根據您的具體需求調整代碼。