Jump to content

while loop in a foreach loop.... semi-results!


suttercain

Recommended Posts

Good evening fellow insomniacs.

 

I am echoing a mysql database result which is stored in the database as such "Superman, Batman, Wonder Woman, etc"

 

I am using the explode to split the into an array using the comma as the delimiter.

 

Then I am trying to get it so if I click on Superman I am taken to the Superman profile page... Batman I go to the Batman profile page.

 

This is the code I am using:

if ($row['characters'] == !NULL) {
		  $people = explode (", ", $row['characters']);
		  echo "<b>CHARACTER(S):</b><br><font color='#263B5A'>" ;
		  sort ($people);
		  foreach ($people as $key=> $val) {
		  $rez = mysql_query ("SELECT name, character_id FROM characters");
		  while ($row = mysql_fetch_assoc($rez)){
		  echo "<a href='view_characters.php?id={$row['character_id']}'>" . $val . "</a><br>";
				}
			}
		  echo "</font><br><br>";
		  }

 

It echos out the following:

 

Batman <---Link to id 1 //Not Correct

Batman <---Link to id 2 // Correct

Batman <---Link to id 3 //Not Correct (No link to 3 should even appear)

Superman <---Link to id 1 // Correct

Superman <---Link to id 2 //Not Correct

Superman <---Link to id 3 //Not Correct (No link to 3 should even appear)

 

which is partually correct... but I want it to echo each only 1 time:

Batman

Superman (not three times each)

 

It feels like I am so close but I can't get it.

 

Any advice or suggestions?

 

Thanks

 

Link to comment
Share on other sites

Try this

 

$val_escaped = mysql_real_escape_string($val);
$rez = mysql_query ("SELECT name, character_id FROM characters WHERE name = '$val_escaped'") or die(mysql_error());

 

The die() is just to make sure there's no errors in your query.

 

You could do it with a single query as well, which will be more complex but also more efficient.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.