使用PHP連接數據庫的代碼可以按照以下步驟編寫:
mysqli_connect()
函數連接到數據庫。該函數需要提供數據庫服務器的主機名、用戶名、密碼和數據庫名稱作為參數。示例代碼如下:$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "mydb";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("連接失敗: " . mysqli_connect_error());
}
mysqli_query()
函數來執行查詢,并使用mysqli_fetch_assoc()
函數來獲取結果集中的數據。示例代碼如下:$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "
";
}
} else {
echo "0 結果";
}
mysqli_close()
函數來關閉連接。示例代碼如下:mysqli_close($conn);
綜合起來,完整的PHP連接數據庫的代碼如下所示:
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "mydb";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("連接失敗: " . mysqli_connect_error());
}
$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "
";
}
} else {
echo "0 結果";
}
mysqli_close($conn);
以上代碼演示了連接到數據庫、執行查詢并輸出結果的過程。根據實際需求,你可以根據需要執行其他操作,如插入、更新或刪除數據。