要使用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();
?>
根据需要修改示例代码中的数据库连接信息和查询语句。