【发布时间】:2014-02-18 23:01:48
【问题描述】:
试图将我的旧 mysql 查询转换为 mysqli 准备好的语句。除了一件事,我已经弄清楚了一切。如何获取存储为数组的查询结果?我以前是这样的:
$sql = "SELECT * FROM Users";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result) {
// do stuff
}
现在我有以下代码。在这种情况下,我的数组是一条记录,所以我不需要遍历它,但我想将它作为一个数组保存,以便我可以引用它的字段名称。另外,我还有其他查询会返回多条记录,所以我需要迭代。
$sql = "SELECT * FROM Users
WHERE (LOWER(first_name)=LOWER(?) && LOWER(last_name)=LOWER(?))";
$stmt = mysqli_stmt_init($link);
$this_user;
if (mysqli_stmt_prepare($stmt, $sql)) {
/* Bind the input parameters to the query */
mysqli_stmt_bind_param($stmt, 'ss', $first_name, $last_name);
/* execute query, store results in an array */
mysqli_stmt_execute($stmt);
$result = mysqli_fetch_array($stmt);
if (mysqli_num_rows($result) == 0) {
mysqli_stmt_close($stmt);
mysqli_close($link);
$tag_result = "failure";
$tag_message = "No matching user found";
echo encodeJSONObj($tag_result, $tag_message);
die();
}
if (mysqli_num_rows($result) > 1) {
mysqli_close($link);
$tag_result = "failure";
$tag_message = "Multiple records found for this user.";
echo encodeJSONObj($tag_result, $tag_message);
die();
}
$this_user = mysqli_fetch_array($result);
/* close statement */
mysqli_stmt_close($stmt);
}
$id = $this_user['id'];
$first_name = $this_user['first_name'];
$last_name = $this_user['last_name'];
// and so on...
谁能告诉我我做错了什么?谢谢!
编辑:非常感谢 Phil,我修改了我的代码。但是,即使我的输入参数应该正好返回 1 行,我似乎仍然返回 0 行。这是我所拥有的:
$sql = "SELECT id, first_name, last_name, group_id, email, cell
FROM Users
WHERE (first_name=? && last_name=?)";
$stmt = mysqli_stmt_init($link);
if (mysqli_stmt_prepare($stmt, $sql)) {
/* Bind the input parameters to the query */
mysqli_stmt_bind_param($stmt, 'ss', $first_name, $last_name);
/* execute query, bind result, and fetch value */
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $first_name, $last_name, $group_id, $email, $cell);
mysqli_stmt_fetch($stmt);
if (mysqli_stmt_num_rows($stmt) == 0) {
mysqli_stmt_close($stmt);
mysqli_close($link);
echo "No results returned";
die();
}
...
}
当它应该找到 1 行并跳过该块时,它总是输出 No results returned。我已经盯着这个看了很长时间,但我就是看不出我做错了什么。
【问题讨论】:
-
为什么我会得到一个-1?谢兹!
-
显然因为这个问题没有显示任何研究工作,因为它写在投票按钮工具提示中
-
在尝试获取任何内容或计算行数之前,您需要
execute()准备好的语句。我建议你阅读这个 - php.net/manual/… -
谢谢,@Phil。这包括在我的许多尝试中,但我得到了相同的结果。我没有在此处包含它,但我将编辑我的帖子以显示我所做的。
-
这应该会引发错误,因为您将
mysqli_stmt传递给mysqli_fetch_array需要mysqli_result。我会说您的error_reporting太低和/或display_errors已禁用。您还尝试将数组传递给mysqli_num_rows,这也不起作用
标签: php arrays mysqli prepared-statement