【问题标题】:Simple Prepared Statement Not Working简单的准备好的语句不起作用
【发布时间】:2016-08-17 11:58:42
【问题描述】:

我正在尝试从我的本地 MySQL 数据库返回一些数据,如下示例 1 on this page

数据库和表都存在,当我使用 PhpMyAdmin 运行查询时,我成功返回了 5 个结果。

我的页面名为 test.php,每当我访问该页面时,我只能看到“connected”这个词。

我的代码如下;

// Create connection
$conn = new mysqli('localhost', 'user', 'password', 'database'); 
// Check connection
if ($conn->connect_errno > 0) {
    die('Unable to connect to database [' . $conn->connect_error . ']');
} else {
    echo "connected </br>";
}

/* prepare statement */
if ($stmt = $conn->prepare("SELECT Status FROM hostloadslog LIMIT 5")) {
    $stmt->execute();

    /* bind variables to prepared statement */
    $stmt->bind_result($col1);

    /* fetch values */
    while ($stmt->fetch()) {
        printf("%s %s\n", $col1);
    }

    /* close statement */
    $stmt->close();
}

任何帮助或建议将不胜感激。

【问题讨论】:

  • 准备后检查错误
  • 我很确定您不能将 prepare 语句放在 if 语句中。不过,您可以将执行放在 if 语句中。
  • 看看$col1 的样子:printf("%s %s\n", $col1); 在几个方面是错误的:有 2 个占位符,但只传递了 1 个值,而 $col1 不是像你一样的字符串似乎认为是
  • @Robert nope 可以按照documentation 执行此操作。
  • @johnny_s NP,不知道你为什么被否决,不过我会投反对票

标签: php mysql oop mysqli


【解决方案1】:

所以基本上,问题在于printf的使用:

printf("%s %s\n", $col1);

失败,因为您使用了 2 个占位符,但只传递了一个字符串。将其更改为任一

echo $col1 . PHP_EOL;
//or
printf("%s\n", $col1);

要更轻松地调试这样的代码,您可以将error_reporting 设置为-1(或在ini 文件中设置为E_STRICT|E_ALL),并将display_errors 设置为on

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 2015-10-11
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多