Kelset Posted October 4, 2006 Share Posted October 4, 2006 Hey all!Well this might sound really simple but I have not been able to firgure it out and thought I would ask you find folks.What I'm doing is querying a MySQL database and getting results then looping through the results.//Sample of my code$query = "SELECT * FROM there";$result = mysql_query($query);Ok here is where I don't understand, I use the while loop to loop through the results which looks like this//Sample of my codewhile ($row = mysql_fetch_array($result)) {Now I want to check and see if anything is in results I tried //Sample of my codeif (!$results) {}but this does not seem to work for me, I'm assuming something always gets passed back even if null.So I tried something like the follow code//Sample of my code$row = mysql_fetch_array($query);if (!$row) { //Display message}else{ while ($row = mysql_fetch_array($result)); {}Now I know I'm over writing the var $row but I thought this would not matter, even if it was bad coding.This works but the first record does not display when I do it this way.So do I have to use a for() loop? get the number of rows and loop with for(). Just thought I would askand see what people thought or how maybe some of you loop through your results.Cheers!Stephen Link to comment https://forums.phpfreaks.com/topic/23033-looping-through-mysql-result/ Share on other sites More sharing options...
trq Posted October 4, 2006 Share Posted October 4, 2006 You want to check your result before the loop. eg;[code=php:0]<?php // connect to db. $sql = "SELECT * FROM db"; $result = mysql_query($sql); if ($result) { if (mysql_num_rows($result)) { while ($row = mysql_fetch_assoc($result)) { // display. } } else { echo "no results found"; } } else { echo "query failed ".mysql_error(); }?>[/code] Link to comment https://forums.phpfreaks.com/topic/23033-looping-through-mysql-result/#findComment-104032 Share on other sites More sharing options...
Kelset Posted October 4, 2006 Author Share Posted October 4, 2006 Thanks for the help that should do the trick.Cheers!Stephen Link to comment https://forums.phpfreaks.com/topic/23033-looping-through-mysql-result/#findComment-104034 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.