我正在准备我的mysql查询以试图提高安全性,但是当我尝试获取预准备语句的结果时,我遇到了问题。我已经研究了错误的原因,但是许多示例使用复杂的代码,我不知道如何将解决方案应用于我的代码。
错误
mysqli_fetch_array()期望参数1为mysqli_result,在
中给出null我的代码
$query = "SELECT cid, user1, user2 FROM convotable
WHERE user1 = ? OR user2 = ? ORDER BY createtime ASC";
$stmt = mysqli_prepare($dbc, $query);
if ($stmt) {
mysqli_stmt_bind_param($stmt, "ii", $user1, $user2);
mysqli_stmt_execute($stmt);
while($row = mysqli_fetch_array($stmt)){
$cid = $row['cid'];
$user1 = $row['user1'];
$user2 = $row['user2'];
}
}
答案 0 :(得分:0)
尝试这种方式并设置您在 mysqli_stmt_bind_param()
中绑定的变量 $query = "SELECT cid, user1, user2 FROM convotable
WHERE user1 = ? OR user2 = ? ORDER BY createtime ASC";
$stmt = mysqli_prepare($dbc, $query);
if ($stmt)
{
mysqli_stmt_bind_param($stmt, "ii", $user1, $user2);
$user1=1; //set variable
$user2=2; //set variable
mysqli_stmt_execute($stmt);
while($row = mysqli_fetch_array($stmt))
{
$cid = $row['cid'];
$user1 = $row['user1'];
$user2 = $row['user2'];
}
}
答案 1 :(得分:0)
它可能不是您所需要的,但我发现使用PDO(替代mysqli)更简单明了:
<?php
$dsn = 'mysql:host=localhost;dbname=DBNAME;charset=utf8';
$user = 'user';
$pass = 'pass';
$db = new PDO($dsn, $user, $pass);
$user1 = '123';
$user2 = '234';
$query = "SELECT cid, user1, user2 FROM convotable
WHERE user1 = ? OR user2 = ? ORDER BY createtime ASC";
$stmt = $db->prepare($query);
$stmt->bindParam(1, $user1, PDO::PARAM_INT);
$stmt->bindParam(2, $user2, PDO::PARAM_INT);
if (!$stmt->execute()) {
echo 'something went wrong';
die;
}
print_r($stmt->fetchAll());