Jump to content

Warning: Invalid argument supplied for foreach() in


WesleyA

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?

Link to comment
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.

Link to comment
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'];

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...