1

I have the below MySQL query which is returning bool false when doing var_dump. The mySQL statement is correct as I tested in phpMyAdmin. Any suggestions to fix this please?

<?php
    $sql = "SELECT enBody FROM page WHERE pageName='wine'";
    $en = $db->query($sql);

    var_dump($enOutput=mysqli_fetch_assoc($en));
    var_dump($en);//returns bool false too
    while($enOutput=mysqli_fetch_assoc($en)) :
        $enDisplay=$enOutput['enBody'];                 
        echo $enDisplay;
    endwhile; 
Marius
  • 33
  • 4

3 Answers3

0

The problem was with the connection string. There was the database name which was different, missing one capital character....stupid me. apologies and thanks all

Marius
  • 33
  • 4
-1

The best guess would be SQL query is unable to find the requested rows so it's returning by assuming you don't have any error in sql query. if You aren't sure about query then use this to check by replacing the query with this

$sql = "SELECT enBody FROM page WHERE pageName='wine'";
$result= $db->query($sql) or die(mysqli_error($db));

null and mysqli_fetch_assoc only accepts mysqli result

So you just need to put a basic if else statement check whether the SQL Query has returned result or not

Try this and let me know if it works or not

I basically just used a function mysqli_num_rows which returns the number of rows fetched by query and followed by conditional to check

$sql = "SELECT enBody FROM page WHERE pageName='wine'";
$result= $db->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
       print_r($row);

    }
} else {
    echo "0 results";
}
Prince Arora
  • 354
  • 1
  • 6
  • 20
-1

You are mixing Object oriented style with Procedural style.

While using Object oriented style you should not use mysqli_* functions as these belongs to Procedural style.

For Procedural style refer: http://php.net/manual/en/function.mysqli-connect.php

For Object oriented style refer: http://php.net/manual/en/mysqli.construct.php

For you code:

Object oriented style:

<?php
$sql = "SELECT enBody FROM page WHERE pageName='wine'";

if($en = $db->query($sql)):
    /* fetch associative array */
    while($enOutput=$en->fetch_assoc($en)) :
        $enDisplay=$enOutput['enBody'];                 
        echo $enDisplay;
    endwhile; 
    /* free result set */
    $en->free();
endif;

Also, for fetch_assoc, refer: http://php.net/manual/en/mysqli-result.fetch-assoc.php

Ketan Yekale
  • 2,108
  • 3
  • 26
  • 33