【问题标题】:Query working normally but not working in prepared statements查询正常工作,但在准备好的语句中不工作
【发布时间】:2014-07-04 23:43:19
【问题描述】:

我有以下准备好的语句代码

// Get the data about the file
$stmt = $mysqli->prepare("SELECT * FROM file WHERE generated_name = ?");
$stmt->bind_param('s', $generated_name);
$stmt->execute();
if($stmt->num_rows == 0) return 'Error';

上面的代码不起作用,它总是返回一个错误,即使它不应该受到影响_rows 也奇怪地返回 -1。但是,如果我离开准备好的方法并进行正常查询..它可以完美运行

// Get the data about the file
$result = $mysqli->query("SELECT * FROM file WHERE generated_name = '$generated_name'");
if($result->num_rows == 0) return 'Error';

此代码运行良好,不会返回错误。我不知道出了什么问题。您能找出错误吗?

【问题讨论】:

    标签: php mysql sql mysqli prepared-statement


    【解决方案1】:

    执行后可以使用store_result

    $stmt->store_result();
    $rows= $stmt->num_rows;
    if($rows > 0)...
    

    【讨论】:

    • 这在某些 php 安装中不受支持,例如 HipHopVirtualMachine,它也不支持 get_result()
    【解决方案2】:

    我相信您必须执行“获取”才能实际获取行; http://www.php.net/manual/en/mysqli.prepare.php

    尝试添加这个;

       $stmt->fetch();  
    

    像这样;

    // Get the data about the file
    $stmt = $mysqli->prepare("SELECT * FROM file WHERE generated_name = ?");
    $stmt->bind_param('s', $generated_name);
    $stmt->execute();
    $stmt->fetch();
    if($stmt->num_rows == 0) return 'Error';  
    

    【讨论】:

    • 可能有助于解释您必须调用fetch() 的原因,因为请记住您必须在execute() 之后选择bind_result() 才能将结果绑定到变量。如果它自动获取结果,您将没有机会绑定变量。
    • 好点 r3wt,如果您打算实际获取数据,您将需要使用 bind_result。
    【解决方案3】:

    我相信 PHP 手册中关于num_rowsthis 评论解释了这一点。引用:

    如果你不使用mysqli_stmt_store_result(),并且立即调用 这个函数在执行一个准备好的语句后,这个函数将 通常返回 0,因为它无法知道有多少行 结果集,因为结果集还没有保存在内存中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      相关资源
      最近更新 更多