0

I got php fatal error after transfer server with php v5.6.19, before that I had no problem at all with following script

Fetch data from db table:

function get_department_list($mysqli)
{
    $sql = $mysqli->query("SELECT * FROM `dept` ORDER BY `dept_id` ASC");

    if($sql->num_rows > 0){
        return $sql;
    }else{
        return false;
    }
}

Populate data in HTML:

<ul class="department overflow-scroll text-center">
    <?php
    $shop = new Shop;

    $depts = $shop->get_department_list($mysqli);
    while($dept = $depts->fetch_object()){
        echo '<li><a href="'.baseurl.'/shop/'.strtolower(str_replace('\'','',$dept->dept_name)).'">'.$dept->dept_name.'</a></li>';
    }
    ?>
</ul>

In the end I got an error:

Fatal error: Call to a member function fetch_object() on boolean in C:\xampp\htdocs\project\include\header.php on line 206

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Lisa8
  • 177
  • 2
  • 2
  • 9
  • Your function `get_department_list` is returning false, which is assigned to `$depts`, so when you try to `fetch_object()` it throws that error. You may want to print out why `$sql->num_rows` is not > 0 – avip Mar 22 '16 at 06:53

2 Answers2

4

First, you are returning a boolean from your function. So, no wonder PHP says you so.

Second, you should keep the matters separated. a function that works with mysqli should keep all mysqli stuff inside. An return just an array, that can be used anywhere without the need to call mysqli functions again.

function get_department_list($mysqli)
{
    $sql = $mysqli->query("SELECT * FROM `dept` ORDER BY `dept_id` ASC");
    return $sql->fetch_all();
}

And then use not while but foreach

foreach ($depts as $dept) ...

Besides (and more for the people who may chance to land on this question looking for an answer to their question) you should always set proper error reporting for mysqli, like it shown in this answer

Community
  • 1
  • 1
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
0

Update your while loop for that case when you get false from $shop->get_department_list() call

updated while like this check for $depts if any data then get $dept:

while($depts && $dept = $depts->fetch_object()){
itzmukeshy7
  • 2,669
  • 1
  • 21
  • 29