$servername = "localhost"; // 服務(wù)器名 $username = "username"; // 用戶名 $password = "password"; // 密碼 $dbname = "myDB"; // 數(shù)據(jù)庫名 // 創(chuàng)建連接 $conn = new mysqli($servername, $username, $password, $dbname); // 檢測(cè)連接 if ($conn->connect_error) { die("連接失敗: " . $conn->connect_error); } echo "連接成功";
2. 查詢數(shù)據(jù) 要查詢數(shù)據(jù)庫中的數(shù)據(jù),您可以使用mysqli_query函數(shù)。下面的代碼顯示了如何查詢名為“myGuests”的數(shù)據(jù)庫中的數(shù)據(jù)表“guests”中的所有數(shù)據(jù)。$sql = "SELECT * FROM guests";
$result = $conn->query($sql);
if ($result->num_rows >0) {
// 輸出每行數(shù)據(jù)
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " . $row["email"]. "
";
}
} else {
echo "0 結(jié)果";
}
$sql = "INSERT INTO guests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "新記錄插入成功";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
$sql = "UPDATE guests SET lastname='Doe' WHERE id=2"; if ($conn->query($sql) === TRUE) { echo "記錄更新成功"; } else { echo "Error updating record: " . $conn->error; }
5. 刪除數(shù)據(jù) 要從數(shù)據(jù)庫中刪除數(shù)據(jù),您可以使用mysqli_query或mysqli_prepare函數(shù)。下面的代碼演示了如何從名為“myGuests”的數(shù)據(jù)庫中的數(shù)據(jù)表“guests”中刪除數(shù)據(jù)。$sql = "DELETE FROM guests WHERE id=3"; if ($conn->query($sql) === TRUE) { echo "記錄刪除成功"; } else { echo "Error deleting record: " . $conn->error; }
總結(jié) MySQL是一種強(qiáng)大的數(shù)據(jù)庫管理系統(tǒng),可供開發(fā)人員使用。如上所述,通過使用mysqli連接函數(shù)、mysqli_query和mysqli_prepare等函數(shù),您可以輕松地連接、查詢、插入、更新和刪除數(shù)據(jù)。希望這篇文章能將MySQL數(shù)據(jù)庫操作的一些基礎(chǔ)知識(shí)介紹給您。