Echo row when $variable is duplicate but primary key is unique
I'm creating a list of stores within cities. So where there's only one store in a city, I want it to display just the one result. When there are two or more stores within the city, I want it to display the information on the multiple stores. Here's what I have:
$result = mysql_query("SELECT * FROM stores where StoreID=$id order by city");
if (!$result) {
die('Invalid query: ' . mysql_error());
$id=mysql_result($result,"StoreID");
mysql_close();
}
<?php echo "$city"; ?>
<?php echo "$street"; ?> etc.
This gives me just one result and I'm not sure how to modify it to look for multiple records. I'm a PHP/MySql beginner so I real开发者_开发知识库ly appreciate your help and apologize if this is a stupid question or ridiculous question. Thank you in advance for your help!
Use this basic loop:
<?while($row = mysql_fetch_assoc($result):?>
city: <?=$row['city']?><BR>
State: <?=$row['state']?><BR>
<?endwhile;?>
Get rid of the mysql_result()
part - use mysql_fetch_assoc()
it's easier.
Also, you should be using the http://www.php.net/mysqli library instead of MySQL in PHP.
PS. I like short tags, but you can change to long tags if you prefer.
Also instead of:
$result = mysql_query("SELECT * FROM stores where StoreID=$id order by city");
if (!$result) {
die('Invalid query: ' . mysql_error());
I like:
$result = mysql_query("SELECT * FROM stores where StoreID=$id order by city") or die('Invalid query: ' . mysql_error());
It's easier to read.
$result = mysql_query("SELECT * FROM stores where StoreID=$id order by city");
if (!$result) {
die('Invalid query: ' . mysql_error());
}else{
while($row = mysql_fetch_assoc($result)){
echo $row['city']." : ".$row['street']."<br />";
}
}
while() is fetching results step by step, so it will give it your result
精彩评论