Mysqli使用预准备语句获取数组

时间:2015-01-11 18:56:02

标签: php mysql mysqli

我正在准备我的mysql查询以试图提高安全性,但是当我尝试获取预准备语句的结果时,我遇到了问题。我可以成功获取一行数据但是我没有成功获取数据数组。我所做的所有研究都提供了不工作或太复杂的例子。

我当前的代码

if ($stmt = $dbc->prepare("SELECT city FROM users WHERE id = ? LIMIT 1")) {
$stmt->bind_param('i', $id);  // Bind id to parameter.
$stmt->execute();    // Execute the prepared query.
$stmt->store_result();

 // get variables from result.
$stmt->bind_result($city);
$stmt->fetch();
}

这是我当前的代码,只返回一个结果。

1 个答案:

答案 0 :(得分:1)

好吧,让我们看看,
首先,你将你的选择查询限制为1个结果,这就是为什么它只返回1个结果,第二,你没有使用while循环遍历你的结果,试试这个:

$stmt = $dbc->prepare("SELECT city FROM users WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($city);
while($stmt->fetch()){
    echo $city;
}

但请记住,您的查询可能只会返回1个值,因为ID可能是独一无二的

相关问题