-1

can anyone help me on this. I'm trying to fetch all the data from table. but it keeps returning as boolean.

<?php
    $con = mysqli_connect("localhost", "root", "", "student");

    $query = "SELECT * FROM `announcement` ORDER BY `announce_id` DESC";

    $result = mysqli_query($con, $query);

    while($row = mysqli_fetch_assoc($result)){
        $data[] = $row;
    }

    echo json_encode($data);
?>

The error given was:

> Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result,
> boolean given in D:\Xampp\htdocs\student\announcement.php on line 8
> 
> Notice: Undefined variable: data in
> D:\Xampp\htdocs\student\announcement.php on line 12 null
  • always check for errors `($con, $query) or die($con->error)` – Kevin Sep 27 '16 at 02:47
  • 2
    your query failed, it returned boolean false –  Sep 27 '16 at 02:55
  • Possible duplicate of [mysqli\_fetch\_array()/mysqli\_fetch\_assoc()/mysqli\_fetch\_row() expects parameter 1 to be resource or mysqli\_result, boolean given](http://stackoverflow.com/questions/2973202/mysqli-fetch-array-mysqli-fetch-assoc-mysqli-fetch-row-expects-parameter-1) – dhruv jadia Sep 27 '16 at 03:56

2 Answers2

0

Please make sure you have a data in "announcement" Table.

You can check the number of rows return in the result set by using the mysqli_num_rows() function.

Try this:

$con = mysqli_connect("localhost", "root", "", "student");
$query = "SELECT * FROM `announcement` ORDER BY `announce_id` DESC";
$result = mysqli_query($con, $query);

$rowcount = mysqli_num_rows($result); //returns number of rows

if($rowcount > 0) {
  while($row = mysqli_fetch_assoc($result)){
    $data[] = $row;
  }
  echo json_encode($data);
}

Let us know incase of any query/concern for the same.

AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57
0

because mysqli_query returned false, $result contains bool(false), and mysqli_fetch_assoc needs a mysqli_result object, and it complained when you gave it a bool instead. we don't know why mysqli_query returned false, and since you don't have error reporting enabled, PHP won't tell you why. you need error checking in your code to catch this earlier, and make php tell you what's wrong. easiest way to do that: start your script with

<?php
error_reporting(E_ALL);
if(!mysqli_report(MYSQLI_REPORT_ALL)){
throw new RuntimeException("unable to set mysqli_report to MYSQLI_REPORT_ALL !");
}

i would also recommend to run an error handler converting errors to exceptions, like this

function exception_error_handler($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting
        return;
    }
    throw new ErrorException($message, 0, $severity, $file, $line);
}
set_error_handler("exception_error_handler");

now php should give a detailed report whenever an error occurred, including why your mysqli_query returned false.

hanshenrik
  • 19,904
  • 4
  • 43
  • 89