Jump to content

Associative Arrays and Loops


coolego1

Recommended Posts

Hello,

I am trying to make database calls on what will potentially be a very large database.  I would like to receive query results from the database using mysql_fetch_array() to get an associative array. Once I have this array, I want to show certain fields using my own formatting.  If there are no fields, I want to show a "No Results" message.  My code thusfar looks like this, and it does nothing if there is an invalid database query:

 

	$result = mysql_query($sql, $connection);
	if ($result) {
		while ($list = mysql_fetch_array($result, MYSQL_ASSOC)) {
			print $list['title'];
			print "<br>";
			print $list['pages'];
			print "<br><br>";
		}
	} else {
		echo "No Results Found";
	}

 

This will show the information but will not respond if there is nothing to show...  Help?

Link to comment
https://forums.phpfreaks.com/topic/57799-associative-arrays-and-loops/
Share on other sites

$result = mysql_query($sql, $connection);

$value=mysql_fetch_assoc($result, MYSQL_ASSOC);

if(!$value)

{

while ($list = $value)

{

print $list['title'];

print "<br>";

print $list['pages'];

print "<br><br>";

}

}

else

{

echo "No Results Found";

}

 

 

you can also have it like this but theres still more

teng that only adds more unneeded parts to the script.  Also since you using mysql_assoc you can just say in the while foreach($list as $key => $value)

echo $key.": ".$value."<br/>";

 

then outside it echo another few breaks to separate it all out or do what you like.

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.