要将MySQLi绑定结果中的一个字段放入数组中,以便使用in_array()
函数进行匹配,你可以按照以下步骤操作:
mysqli_stmt_bind_result()
函数,可以将预处理语句的结果绑定到变量上。以下是一个示例代码,展示如何将MySQLi绑定结果中的一个字段放入数组,并使用in_array()
函数进行匹配:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 预处理语句
$stmt = $conn->prepare("SELECT id FROM users WHERE status = ?");
$stmt->bind_param("i", $status);
$status = 1; // 假设我们要查找状态为1的用户
$stmt->execute();
// 绑定结果
$stmt->bind_result($id);
// 存储结果的数组
$ids = array();
// 获取所有结果并存储到数组中
while ($stmt->fetch()) {
$ids[] = $id;
}
// 关闭语句和连接
$stmt->close();
$conn->close();
// 使用in_array()检查某个ID是否存在
$check_id = 5;
if (in_array($check_id, $ids)) {
echo "$check_id 存在于数组中";
} else {
echo "$check_id 不存在于数组中";
}
?>
mysqli_stmt_error()
函数获取详细的错误信息。in_array()
之前,数组已经被正确填充。in_array()
的第三个参数(strict),如果设置为true
,则进行严格类型比较。通过以上步骤和示例代码,你可以有效地将MySQLi绑定结果中的一个字段放入数组,并使用in_array()
函数进行匹配。
领取专属 10元无门槛券
手把手带您无忧上云