要使用PHP操作MySQL數(shù)據(jù)庫,您需要遵循以下步驟:
mysqli
或PDO
擴展。以下是使用這兩種擴展的示例代碼:使用mysqli
擴展:
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 創(chuàng)建連接
$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);
// 設(shè)置 PDO 錯誤模式為異常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "連接失敗: " . $e->getMessage();
}
檢索數(shù)據(jù)(SELECT):
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 輸出數(shù)據(jù)
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 結(jié)果";
}
插入數(shù)據(jù)(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;
}
更新數(shù)據(jù)(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;
}
刪除數(shù)據(jù)(DELETE):
$sql = "DELETE FROM your_table WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "刪除成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
使用mysqli
擴展關(guān)閉連接:
$conn->close();
使用PDO
擴展關(guān)閉連接:
$conn = null;
這就是使用PHP操作MySQL數(shù)據(jù)庫的基本方法。請根據(jù)您的需求調(diào)整代碼示例。