【问题标题】:How do I get a result from a prepared statement using PHP? [duplicate]如何使用 PHP 从准备好的语句中获取结果? [复制]
【发布时间】:2014-05-11 16:37:42
【问题描述】:

我能够从标准 SQL 查询中获取结果,但是对于准备好的语句,我很好,直到从查询中获取结果。

作为后台,查询将产生多于一行。

$sql = "SELECT * FROM blog WHERE ID=?";

if (!$stmt = $con -> prepare($sql)) {
    echo "Prepare failed: (" . $con->errno . ") " . $con->error;
}

if (!$stmt->bind_param("i", $_GET["ID"])) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

while($row = $stmt->fetch_assoc()){
    $blog_title = $row['title'];
    $blog_body = $row['body'];
    $blog_blurb = $row['blurb'];
    $blog_date = $row['posted'];
    $blog_tags = $row['tags'];  
} 

这会导致

致命错误:调用未定义的方法 mysqli_stmt::fetch_assoc()

但是,我尝试了 PHP 手册中概述的内容,但没有成功。

【问题讨论】:

  • 尝试var_dump(get_class_methods($stmt))查看可用的方法。
  • 使用while ($row = $stmt->fetch()) {
  • 好笑,但函数调用完全一样——get_result()
  • @Loïc 当我尝试得到"array(17) { [0]=> string(11) "__construct" [1]=> string(8) "attr_get" [2]=> string(8) "attr_set" [3]=> string(10) "bind_param" [4]=> string(11) "bind_result" [5]=> string(5) "close" [6]=> string(9) "data_seek" [7]=> string(7) "execute" [8]=> string(5) "fetch" [9]=> string(12) "get_warnings" [10]=> string(15) "result_metadata" [11]=> string(8) "num_rows" [12]=> string(14) "send_long_data" [13]=> string(11) "free_result" [14]=> string(5) "reset" [15]=> string(7) "prepare" [16]=> string(12) "store_result" } "
  • 正如@AbhikChakraborty 提到的,你应该使用fetch()

标签: php arrays mysqli prepared-statement


【解决方案1】:

这里有更好的方法。

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mydatabase = new mysqli('localhost', 'root', '', 'database');

$id = $_GET['id'];
$stmt = $mydatabase->prepare("SELECT * FROM `blog` where ID = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result(); //get the results

while ($row = $result->fetch_assoc()) {
    echo $row['whatever']; //do whatever here
}

如果您的安装中不存在get_result(),请使用:

$stmt->bind_result($column1, $column2);
while ($stmt->fetch()) {
    echo $column1;
    echo $column2;
}

【讨论】:

  • 使用此代码,我得到“致命错误:调用未定义的方法 mysqli_stmt::get_result()”在线“//获取结果”
  • 它适用于我的系统,如果它不适用于您的系统,则可能的原因可能是您的 Web 服务器上未安装 MySQL Native Driver (mysqlnd)。在这种情况下,您可以将代码更改为编辑后的版本。
猜你喜欢
  • 1970-01-01
  • 2017-03-26
  • 2023-03-03
  • 2015-10-29
  • 2019-03-05
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多