williamZanelli Posted July 9, 2008 Share Posted July 9, 2008 I was just wondering how I could check an empty result from the database. Say I run the following query and it returns nothing $sql = "Select * from links where user_id = 'Addidas'" $records = mysql_fetch_array($sql) I've seen people write if ($records){ // do something with the result } else{ echo "No items"; } what exactly does if ($records) mean? I'm from a java background, where you would be required to write something like, if(result != nul){... Thanks for your thoughs William PS: Does anyone know of a good, comprehensive tutorial on PHP, outlining the basics, such as above, arrays etc. thanks. Link to comment https://forums.phpfreaks.com/topic/113929-solved-how-to-check-empty-result-from-database-query/ Share on other sites More sharing options...
trq Posted July 9, 2008 Share Posted July 9, 2008 Your example is a little floored, but basically, you need to check returned values from function calls to make sure they contain what you expect. A better example. <?php $sql = "SELECT foo FROM bar"; $result = mysql_query($sql); // check your call to mysql_query succeeded. if ($result) { // check $result holds data if (mysql_num_rows($result)) { // in here it is safe to use $result to display data while ($row = mysql_fetch_assoc($result) { echo $row['foo'] . "<br />"; } } else { // no data found. } } else { // query failed, handle error. } ?> Theres a good link in my signiture if your just getting started. Link to comment https://forums.phpfreaks.com/topic/113929-solved-how-to-check-empty-result-from-database-query/#findComment-585494 Share on other sites More sharing options...
alco19357 Posted July 9, 2008 Share Posted July 9, 2008 <?php $sql = "SELECT foo FROM bar"; $result = mysql_query($sql); // check your call to mysql_query succeeded. if ($result) { // check $result holds data if (mysql_num_rows($result)) { // in here it is safe to use $result to display data while ($row = mysql_fetch_assoc($result) { echo $row['foo'] . "<br />"; } } else { // no data found. } } else { // query failed, handle error. } ?> $sql = "Select * from links where user_id = 'Addidas'"; $records = mysql_query($sql); $records_count = mysql_num_rows($records); if($records_count > 0){ //do functions }else{ //parse error } For this you can check if there is a specific number of returns for instance if($records_count === 1){ and so on Link to comment https://forums.phpfreaks.com/topic/113929-solved-how-to-check-empty-result-from-database-query/#findComment-585503 Share on other sites More sharing options...
williamZanelli Posted July 9, 2008 Author Share Posted July 9, 2008 Great answer Thorpe. That clears up a good few questions. Thanks Will Link to comment https://forums.phpfreaks.com/topic/113929-solved-how-to-check-empty-result-from-database-query/#findComment-585538 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.