简体   繁体   English

mysql_num_rows() 返回 0

[英]mysql_num_rows() returning 0

My $result variable will equal to "Resource id #4" when program executes.当程序执行时,我的 $result 变量将等于“Resource id #4”。 Which clearly means that my mysql_query() was successfully executed.这显然意味着我的 mysql_query() 已成功执行。 But when I call in mysql_num_rows($result), I always get back 0. Although a row does exist, I keep getting a value of 0. Why?但是当我调用 mysql_num_rows($result) 时,我总是返回 0。虽然确实存在一行,但我总是得到 0 的值。为什么?

if (isset($_POST["user"]) && isset($_POST["pass"]))
{
    // prepare SQL
    $sql = sprintf("SELECT 1 FROM users WHERE username='%s' AND password=PASSWORD('%s')",
                   mysql_real_escape_string($_POST["user"]),
                   mysql_real_escape_string($_POST["pass"]));

    // execute query
    $result = mysql_query($sql);


    if ($result === false)
        die("Could not query database");


    $numOfRows = mysql_num_rows($result);

There's nothing obviously wrong with your code.您的代码没有任何明显错误。

The most obvious explanation is that the query being submitted to the database is not returning any rows.最明显的解释是提交到数据库的查询没有返回任何行。

I recommend you add some rudimentary debugging: echo (or vardump or printf) the value of the SQL text $sql prior to submitting it to the database.我建议您添加一些基本的调试:在将 SQL 文本$sql提交到数据库之前回显(或 vardump 或 printf)它的值。

Verify that the SQL text is what you expect to be submitted to the database, and that this query returns a row.验证 SQL 文本是您期望提交给数据库的内容,并且此查询返回一行。

As another step in debugging, I recommend you actually fetch the rows from the resultset, and display the returned rows.作为调试的另一个步骤,我建议您实际从结果集中获取行,并显示返回的行。


I typically assign an alias to literals in the SELECT list, eg我通常为 SELECT 列表中的文字分配一个别名,例如

SELECT 1 AS one FROM ...

But I don't think this would really cause an issue with the mysql_num_rows.但我认为这不会真正导致 mysql_num_rows 出现问题。


I believe earlier versions of PHP defaulted to having "magic quotes" feature being turned (automatically running an addslashes function on strings);我相信早期版本的 PHP 会默认启用“魔术引号”功能(自动在字符串上运行 addlashes 函数); echoing out the generated SQL would show if "double escaping" was a problem or not.回显生成的 SQL 将显示“双重转义”是否有问题。


Addendum附录

An obligatory note here that the mysql_ interface is DEPRECATED, and new development should make use of one of the (much improved) replacements: mysqli or PDO .此处必须注意的是mysql_接口已弃用,新开发应使用其中一个(大大改进的)替代品: mysqliPDO

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

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