Skip to content
Advertisement

PHP/MySQL: Get name for specific ID

I am a beginner to MySQL and Im trying to retrieve a name for a specific ID.

Here is how my database looks like:

I have a table of contacts which contains ID, first and last name.

I want to retrieve the first and last name for a specific ID in the same form.

So I want to end up with a form of options and the option value will be the first name for each ID.

For example:

<form>
<select name="users">
<option value="">Select a person:</option>
<option value="5"> <?php echo "$first $last" ?> </option>
<option value="10"> <?php echo "$first $last" ?> </option>
<option value="15"> <?php echo "$first $last" ?> </option>
</select>
</form>

The values are the ID’s.

and my PHP:

<?php   include("connection.php");

$query="SELECT * FROM contacts";
$result=mysql_query($query);

$num=mysql_numrows($result);

mysql_close();

$i=0;
while ($i < $num) {

$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");

$i++;
}

?>

in my actual example I get the first and last name of the last’s person in the database only.

So how can I retrieve the first and last name for specific ID’s of which I assign in my form (?)

Advertisement

Answer

This is because your while loop is overwriting $first and $last every single time. Try

$users = array();

while ($row = mysql_fetch_assoc($result)) { 
  $users[] = $row;
}

And in HTML (EDITED):

<form>
  <select name="users">
    <option value="">Select a person:</option>
    <?php foreach($users as $row): ?>
      <option value="<?php echo $row['id']; ?>"> <?php echo $row['first'] . " " .  $row['last']; ?> </option>
    <?php endforeach; ?>
  </select>
</form>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement