WesleyA Posted June 8, 2016 Share Posted June 8, 2016 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 More sharing options...
Ingolme Posted June 9, 2016 Share Posted June 9, 2016 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 More sharing options...
WesleyA Posted June 9, 2016 Author Share Posted June 9, 2016 (edited) 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 June 9, 2016 by WesleyA Link to comment Share on other sites More sharing options...
Ingolme Posted June 9, 2016 Share Posted June 9, 2016 $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 More sharing options...
Stancobridge Posted June 9, 2016 Share Posted June 9, 2016 am having this invalid argument supplied for foreach in my site will post it tomorrow am not close to the code now...hope u guys will help Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now