简体   繁体   English

Prepared语句不返回任何结果

[英]Prepared statement returns no results

I have been chasing my tale with this for a long time. 我用这个很长一段时间一直在追逐我的故事。 I have not been able to find an issue with this code: 我无法找到此代码的问题:

 $query = "SELECT * FROM CUSTOMER WHERE username = ?";
 $stmt = $db->prepare($query);
 $stmt->bind_param("s", $username);
 $stmt->execute();
 echo $stmt->num_rows." ".$username;`

The CUSTOMER table in my database has three columns: username, pwd, and email. 我的数据库中的CUSTOMER表有三列:username,pwd和email。 But nonetheless, no results are returned when I assign the $username variable to a value I know exists in the database. 但是,当我将$ username变量分配给我知道存在于数据库中的值时,不会返回任何结果。 I know it exists because this query 我知道它存在是因为这个查询

$results = $db->query("SELECT * FROM CUSTOMER WHERE username ='$username'");
echo $results->num_rows;

Displays one row, which is what is expected. 显示一行,这是预期的。 Can anybody please tell me why my prepared statement will not produce the correct results? 有人可以告诉我为什么我准备好的陈述不会产生正确的结果吗? I have tried several variations of quoting, not quoting, hardcoding the variable's value, but nothing works. 我尝试了几种引用的变体,而不是引用,硬编码变量的值,但没有任何作用。 I am on a university server so I have no control over PHP's or MySQL's settings, but I'm not sure that has anything to do with it. 我在大学服务器上,所以我无法控制PHP或MySQL的设置,但我不确定它与它有什么关系。 It seems like a coding issue, but I can't see anything wrong with the code. 这似乎是一个编码问题,但我看不出代码有什么问题。

num_rows will be populated only when you execute $stmt->store_result(); 只有在执行$stmt->store_result();时才会填充num_rows $stmt->store_result(); .

However, 99.99% of the time you do not need to check num_rows . 但是,99.99%的时间你不需要检查num_rows You can simply get the result with get_result() and use it. 您可以使用get_result()获取结果并使用它。

$query = "SELECT * FROM CUSTOMER WHERE username = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
foreach($result as $row) {
    // ...
}

If you really want to get the num_rows, you can still access this property on the mysqli_result class. 如果你真的想得到num_rows,你仍然可以在mysqli_result类上访问这个属性。

$result = $stmt->get_result();
$result->num_rows;

You've executed the query successfully, but not done anything with the result . 您已成功执行查询,但未对结果执行任何操作。
After $stmt->execute(); $stmt->execute(); , you're looking for $stmt->bind_result($result); ,您正在寻找$stmt->bind_result($result); .

With this, you'll have access to the user's information in the $result variable. 有了这个,您将可以访问$result变量中的用户信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM