chronister Posted December 19, 2006 Share Posted December 19, 2006 Hi everybody,I am trying to select the first letter of a lastname from a database and then display those results. I am doing a sort alphabetical listing and only want the letters that occur in the database to show. Here is the code I have$query="SELECT DISTINCT LEFT(lastname,1) FROM addresses WHERE lastname!='' ORDER BY lastname ASC";$result=mysql_query($query)or die(mysql_error());$num=mysql_num_rows($result);When I echo $num it gives me 7. This is correct. Now the problem. How do I get the results out of this. I have tried mysql_fetch_row, mysql_fetch_object (I realize this is not even supposed to work in this case), mysql_fetch_assoc, and mysql_fetch_array. None of these are giving me the correct results. PHPMYADMIN gives me the correct results, but I cannot get this to display properly in my script. The mysql_fetch_* methods above only return the 1st item.Any Suggestions?Thanks,Nate Link to comment https://forums.phpfreaks.com/topic/31204-solved-mysql_fetch_-problem/ Share on other sites More sharing options...
trq Posted December 19, 2006 Share Posted December 19, 2006 You need a loop if you want all results displayed, its also easier to give your result an alias (see my query).[code=php:0]$query="SELECT DISTINCT LEFT(lastname,1) AS firstletter FROM addresses WHERE lastname!='' ORDER BY lastname ASC";if ($result = mysql_query($query)) { if ($num = mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { // the while will loop over all results. echo $row['firstletter']."<br />"; } }} else { echo mysql_error();}[/code] Link to comment https://forums.phpfreaks.com/topic/31204-solved-mysql_fetch_-problem/#findComment-144279 Share on other sites More sharing options...
chronister Posted December 19, 2006 Author Share Posted December 19, 2006 THANK YOU!!!!!!!!!!!I have been banging my head against a wall for about 2 hours now trying to figure out why I could not get the results out of there. And in 6 minutes and 2 seconds got the answer here. AWESOMEI tried while loops and foreach loops but what I was doing wrong (I think) is I did not have the alias in there to give it a name.This is the first time I have tried using the left() method, was trying to do it with substr(lastname,1,1) which gave me the same results, but still did not have a handle in which to grab the results with.THANKS A MILLION. Link to comment https://forums.phpfreaks.com/topic/31204-solved-mysql_fetch_-problem/#findComment-144282 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.