要使用PHP和MySQLi執行查詢,請遵循以下步驟:
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_db";
// 創建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
query()
方法執行SQL查詢。例如,要執行一個簡單的SELECT查詢,可以這樣做:$sql = "SELECT id, name FROM your_table";
$result = $conn->query($sql);
$rows = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
echo "0 結果";
}
close()
方法來關閉連接。$conn->close();
將這些步驟組合在一起,完整的示例代碼如下:
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_db";
// 創建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM your_table";
$result = $conn->query($sql);
$rows = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
echo "0 結果";
}
$conn->close();
?>
根據需要修改示例代碼中的數據庫連接信息和查詢語句。