Jump to content
Sign in to follow this  
WesleyA

Warning: Invalid argument supplied for foreach() in

Recommended Posts

I have a table which is either empty or has 1 record

 

If the table is empty i cant retrieve info from the database and get an error message.

 

my code:

    $sql = "SELECT id FROM users WHERE id = (SELECT MAX(id)FROM users)";
    $result = $conn->query($sql);
    foreach ( $conn->query($sql) as $row ) {
    $id = $row['id'];

the for each line gives an error message:

 

 

 

 

Warning: Invalid argument supplied for foreach() in

 

how to solve this?

Share this post


Link to post
Share on other sites

That means that the query failed.

 

You should have $result in the foreach() loop, not $conn->query(). Because you're executing the query twice.

 

if $result is false then check $conn->error if you're using MySQLi, use $con->errorInfo() if you're using PDO.

Share this post


Link to post
Share on other sites

can you show what you mean?

 

Im also thinking of making a record pseudo empty (so with only one field) but I wonder if there is a good php solution.

Edited by WesleyA

Share this post


Link to post
Share on other sites

$sql = "SELECT id FROM users WHERE id = (SELECT MAX(id)FROM users)";

$result = $conn->query($sql);

 

if(!$result) {

// SOMETHING WENT HORRIBLY WRONG.

// FIND OUT WHY

echo $conn->error;

exit;

} else {

foreach ( $result as $row ) {

$id = $row['id'];

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...