Jump to content

[SOLVED] mysql_fetch_ problem


chronister

Recommended Posts

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

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]
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. AWESOME

I 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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.