-2

I'm having an issue getting this code to work properly. It is working when a record is found and displays the data but does not execute else and echo when a record in the db is not found. I am guessing is has to do with how I am structuring my code. I have tried this a couple different ways and am having no luck. I am using a sqlite3 database

$recID = '55';

$results2 = $db2->query("SELECT * FROM Movies WHERE TMDBid = '$recID'");

while($row2 = $results2->fetchArray()){

if(!empty($row2['id'])){

$Runtime = $row2['Runtime'];
$Budget = $row2['Budget'];
$Revenue = $row2['Revenue'];
$Production = $row2['Production'];

echo $Runtime.'<br>';
echo $Budget.'<br>';
echo $Revenue.'<br>';
echo $Production.'<br><br>';    

}else{

echo 'No Record Exists';

}
  }

I have tried it this way as well and this way works when no record is found but will not display data when the record exists.

$recID = '55';

$results2 = $db2->query("SELECT * FROM Movies WHERE TMDBid = '$recID'");

if($results2->fetchArray() !== false){

while($row2 = $results2->fetchArray()){

$Runtime = $row2['Runtime'];
$Budget = $row2['Budget'];
$Revenue = $row2['Revenue'];
$Production = $row2['Production'];

echo $Runtime.'<br>';
echo $Budget.'<br>';
echo $Revenue.'<br>';
echo $Production.'<br><br>';    

}

}else{

echo 'No Record Exists';

}
Micha
  • 372
  • 3
  • 13

1 Answers1

1

It's not hitting the ELSE or the ECHO because you're not ever getting into the while. The fetchArray() returns false if there are no records.

In your example:

$recID = '55';

$results2 = $db2->query("SELECT * FROM Movies WHERE TMDBid = '$recID'");

$numrecs = 0;

while($row2 = $results2->fetchArray()){

    $numrecs++;

    $Runtime = $row2['Runtime'];
    $Budget = $row2['Budget'];
    $Revenue = $row2['Revenue'];
    $Production = $row2['Production'];

    echo $Runtime.'<br>';
    echo $Budget.'<br>';
    echo $Revenue.'<br>';
    echo $Production.'<br><br>';    

}

if ($numrecs == 0) {
    echo 'No Record Exists';
}

There are more ways to skin this cat, but you may find this simplest based on the code you have now.

R. Smith
  • 476
  • 4
  • 10
  • Thank you very much for your help. Too be honest I never really thought about it that way as the code not being executed based on `fetchArray()` returning false. – Micha Apr 09 '18 at 21:08