MySQL是一種關(guān)系型數(shù)據(jù)庫,PHP是一種用于服務(wù)器端的腳本語言,它們兩者結(jié)合起來可以實現(xiàn)增刪查改操作。以下是一些示例代碼:
連接數(shù)據(jù)庫:
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 創(chuàng)建連接 $conn = new mysqli($servername, $username, $password, $dbname); // 檢查連接 if ($conn->connect_error) { die("連接失敗: " . $conn->connect_error); }
插入數(shù)據(jù):
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if ($conn->query($sql) === TRUE) { echo "插入成功"; } else { echo "插入失敗: " . $sql . "
" . $conn->error; }
查詢數(shù)據(jù):
$sql = "SELECT * FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows >0) { // 輸出數(shù)據(jù) while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
"; } } else { echo "0 結(jié)果"; }
更新數(shù)據(jù):
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; if ($conn->query($sql) === TRUE) { echo "更新成功"; } else { echo "更新失敗: " . $conn->error; }
刪除數(shù)據(jù):
$sql = "DELETE FROM MyGuests WHERE id=3"; if ($conn->query($sql) === TRUE) { echo "刪除成功"; } else { echo "刪除失敗: " . $conn->error; }
總之,MySQL和PHP是一對強大的組合,可以用來管理和處理大量數(shù)據(jù)。上面的示例代碼只是介紹了一些基本操作,但在實際應(yīng)用中,我們還可以使用更為復(fù)雜的查詢語句和數(shù)據(jù)處理方式。