要使用PHP和MySQLi執(zhí)行查詢,請遵循以下步驟:
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_db";
// 創(chuàng)建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
query()
方法執(zhí)行SQL查詢。例如,要執(zhí)行一個(gè)簡單的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 結(jié)果";
}
close()
方法來關(guān)閉連接。$conn->close();
將這些步驟組合在一起,完整的示例代碼如下:
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_db";
// 創(chuàng)建連接
$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 結(jié)果";
}
$conn->close();
?>
根據(jù)需要修改示例代碼中的數(shù)據(jù)庫連接信息和查詢語句。