<?php
// 连接数据库
$mysqli = new mysqli("localhost", "username", "password", "database");
// 检查连接
if ($mysqli->connect_error) {
die("连接失败: " . $mysqli->connect_error);
}
// 使用 if 语句进行条件判断
$user_id = 1;
$query = "SELECT * FROM users WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 结果";
}
// 关闭连接
$stmt->close();
$mysqli->close();
?>
new mysqli()
方法连接到 MySQL 数据库,并检查连接是否成功。prepare()
方法准备 SQL 查询,并通过 bind_param()
绑定参数,以防止 SQL 注入。execute()
执行查询,并通过 get_result()
获取结果集。if
语句检查查询结果是否有返回行。如果有,遍历并输出每一行的数据;如果没有,输出提示信息。希望这个示例能帮助你理解如何在 PHP 中使用 MySQLi 和 if
语句。
上一篇:mysql删除触发器
下一篇:mysql怎么查看版本
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站