【问题标题】:PHP Error Boolean given instead of object, but I am giving an objectPHP错误布尔给出而不是对象,但我给了一个对象
【发布时间】:2017-12-13 18:22:14
【问题描述】:

我遇到了 fetch assoc 的问题,它返回一个错误,说它需要一个不是布尔值的对象,但我检查了“结果”是一个不是布尔值的对象,这可能是什么原因?

try{
$someSQL = "Call SomeSproc()";
$results = mysqli_query($connection,$someSQL);
}catch(Exception $ex)
{
echo("Error: " .  __LINE__ . " " .$ex);
}

print_r($results);//says I have 14 results
echo gettype($results);//prints object

while($result = mysqli_fetch_assoc($results)) 
{}

这是错误

mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 14 [type] => 0 ) object
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in "path"

【问题讨论】:

  • 很多 php 函数在错误时返回 false。您是否尝试过 if(mysqli_fetch_assoc($results)===false) 来查看发生了什么?
  • 可能是重复的。所以,看看这个帖子stackoverflow.com/questions/11347971/…
  • @MarceloStaudt 我会试试的,你可以从我的代码中看到没有 dodoconr 我的结果没有从 print_r 返回布尔值或 false

标签: php mysqli


【解决方案1】:

您可能在 while 循环期间用一些布尔变量覆盖了 $results 值,因此这可能是您的代码中没有包含的拼写错误。


请仔细检查您的代码,或尝试使用以下example 使用程序样式重写它:

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_assoc($result)) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

这是使用面向对象风格的版本:

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    $result->free();
}

/* close connection */
$mysqli->close();
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 2017-08-31
    • 1970-01-01
    • 2012-06-08
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多