-1

我不明白为什么 $amountOfUsers 显示为 0?

在我转移到 bind_param 函数之前,这曾经可以工作......我只使用 query() instad of prepare。但这要安全得多,我只是很难理解为什么这不起作用,以及如何解决它。

$stmt = $mysqli->prepare("SELECT id, expire, status, username FROM username WHERE username= ?");
$stmt->bind_param('s', $username);
$stmt->execute();

//Counting results. 0 = Invalid, 1 = Valid
$amountOfUsers = $stmt->num_rows;

我得到的错误是: $amountOfUsers 没有正确计算结果的数量。

4

3 回答 3

1
$stmt = $mysqli->prepare("SELECT id, expire, status, username FROM username WHERE username= ?");
$stmt->bind_param('s', $username);
$stmt->execute();
// Store the result (so you can get the properties, like num_rows)
$stmt->store_result();
// Get the number of rows
$amountOfRows = $stmt->num_rows;

// Bind the result to variables
$stmt->bind_result($id, $expire, $status, $db_username);
// Process the variables
while($stmt->fetch()) {
    printf("%d %s %s %s\n", $id, $expire, $status, $db_username);
}
于 2013-09-10T22:51:37.167 回答
0

有时事情并没有按计划进行。检查库中可用的结果代码和错误通常比询问陌生人更有效地进行故障排除,但希望这个陌生人可以帮助......选择以下模式之一:

A:

$result = $stmt->execute();
if (!$result) { /* handle errors */ }

乙:

$stmt->execute();
if ($stmt->errno != 0) { /* handle errors */ }

C(仅用于开发故障排除,而不是您会留下的代码):

$stmt->execute();
print_r($stmt->error_list);

更多信息和相关页面: http ://www.php.net/manual/en/mysqli-stmt.errno.php

于 2013-09-11T08:42:12.040 回答
-2

我一生中永远不会理解为什么 php 用户如此倾向于返回的行数。
特别是如果仅用作标志...如果返回任何数据!

为什么不把返回的数据拿出来看看呢?

$sql  ="SELECT id, expire, status, username FROM username WHERE username= ?s";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if ($row)
{
    // do whatever
}

我也永远不会理解对冗长而多风的代码的倾向。
为什么不让自己成为一个抽象库并将所有内容集中在一行中呢?

$sql = "SELECT id, expire, status, username FROM username WHERE username= ?";
if ($row = $db->getRow($sql))
{
    // do whatever
}
于 2013-09-11T08:34:34.380 回答