0

I have the following PHP which basically gets the result of a MySQL query:

$q2 = "SELECT FIELD FROM TABLENAME WHERE ID = 1;";
$con = new mysqli($server, $user, $pass);
if (mysqli_connect_errno()) 
{
    $error = mysqli_connect_error();
    exit();
}
else
{   
    $res = mysqli_query($con, $q2);
    if ($res)
    {   
        while($row = mysqli_fetch_assoc($res))
        {
            PRINT "THERE WAS A RESULT HERE: "; 
        }
    }
    else
    {
        $error = mysqli_error();
        exit();
    }
    mysqli_free_result($res);   
};
mysqli_close($con);

But on occasions, it will return an empty value. This is valid, based on how the parent application works, but how can I detect that empty row and return "THIS WAS AN EMPTY ROW: "?

air4x
  • 5,618
  • 1
  • 23
  • 36
IGGt
  • 2,627
  • 10
  • 42
  • 63
  • Please define "empty row". Does it mean that no row has been returned? Or that inside one row the *FIELD* was `NULL` or an empty string (`""`)? – hakre Oct 29 '12 at 16:24

4 Answers4

5

You might want to look up mysqli_num_rows() in the PHP manual. It lets you see how many rows are in a result set generated by the previous query. You can use the row count to determine whether to display results or the "no matching results" message.

GordonM
  • 31,179
  • 15
  • 87
  • 129
2

I hope this helps.

if ($res)
{   
    if($res->num_rows) {
        while($row = mysqli_fetch_assoc($res))
        {
           PRINT "THERE WAS A RESULT HERE: "; 
        }
    }
    else {
          PRINT "THERE WAS A EMPTY ROW: "; 
    }
}

Refer: php.net

0

Thanks for that I ended up with:

$q2 = "SELECT FIELD FROM TABLENAME WHERE ID = 1;";
$con = new mysqli($server, $user, $pass);
if (mysqli_connect_errno()) 
{
    $error = mysqli_connect_error();
    exit();
}
else
{   
$res = mysqli_query($con, $q2);

$row_cnt = mysqli_num_rows($res);

if ($row_cnt == 0)
{
        PRINT "THERE WAS NO RESULT: "; 
 }

else
{    
if ($res)
{   
    while($row = mysqli_fetch_assoc($res))
    {
        PRINT "THERE WAS A RESULT HERE: "; 
    }
}
else
{
    $error = mysqli_error();
    exit();
}
mysqli_free_result($res);   
}
};
 mysqli_close($con);
IGGt
  • 2,627
  • 10
  • 42
  • 63
0

My php function query handle:

private function query($sql_query){

        $result = $this->connection->query($sql_query);

        if(!$result){           //query fail
            throw new Exception($this->connection->error.$sql_query);
        }else {//                 "SUCCESS";
            if(!$result->num_rows)
            {
                throw new Exception("THERE WAS NO RESULT: "); 
             }
            for ($res = array(); $tmp = $result->fetch_array(MYSQLI_BOTH);){ 
                $res[] = $tmp;                
            }
           return $res;
        }
    }
ebo
  • 2,717
  • 1
  • 27
  • 22
Noam Rones
  • 13
  • 2