在網站開發中,數據庫是非常重要的一環,而mySQL的應用非常普遍。作為開發者,我們可以通過php來連接、查詢和操作mySQL數據庫。以下是一些常見的使用示例。
鏈接mySQL的示例:
$servername = "localhost"; $username = "username"; $password = "password"; // 創建連接 $conn = new mysqli($servername, $username, $password); // 檢測連接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully";
查詢數據的示例:
$sql = "SELECT id, name, age FROM users"; $result = $conn->query($sql); if ($result->num_rows >0) { // 輸出每行數據 while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"]. "
"; } } else { echo "0 results"; }
插入數據的示例:
$sql = "INSERT INTO users (name, age, email) VALUES ('John Doe', '35', 'johndoe@example.com')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "
" . $conn->error; }
更新數據的示例:
$sql = "UPDATE users SET age='40' WHERE name='John Doe'"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; }
刪除數據的示例:
$sql = "DELETE FROM users WHERE name='John Doe'"; if ($conn->query($sql) === TRUE) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . $conn->error; }
在php中使用mySQL數據庫并不復雜,只需要深入了解它的操作方法。通過以上實例,你可以輕易地開始使用mySQL。
上一篇ajax 提交數組 接收
下一篇mysql端口php