user2371301
user2371301

Reputation: 3474

Multiple rows in mysql fetch

I have a select php script and the portion of it is:

  while($row = mysqli_fetch_array($result))
  {         
  echo "<option>" . $row['firstname'] . $row['lastname'] . "</option>
  }                 
echo "</select>";                       
echo "</div>";

the problem are the rows, I am wanting them to appear in the option as "John Doe" the way it is now is "JohnDoe"

I have tried changing it to: . $row['firstname'] . "&nbsp;" . $row['lastname'] . but that would cause problems later on in the program where it wouldn't read the name as John Doe it would read it as John Doe for some reason. (extra space)

Upvotes: 2

Views: 281

Answers (8)

srakl
srakl

Reputation: 2619

Or, in your MySql query you could do something like this.

$sql = "SELECT CONCAT(`firstname`, ' ', `lastname`) AS `fullname` FROM `TABLENAME`";

and your PHP loop would look like this

 while($row = mysqli_fetch_array($result))
 {         
     echo "<option>" . trim($row['fullname']) . "</option>"; //just incase, we trim it
 } 

Upvotes: 0

Guillaume Chevalier
Guillaume Chevalier

Reputation: 10888

You'll need to fix it later in the program and echo a space like you want firstly.

Search for double spaces in the string and replace them with one space :

$str ='John  Doe'
$str = str_replace("  ", " ", $str);

Upvotes: 0

no92
no92

Reputation: 129

The problem with your code is that $row['lastname'] is directly appended to $row['firstname']. To fix that, just put a space in between:

echo "<option>".$row['firstname']." ".$row['lastname']."</option>";

Upvotes: 0

Orangepill
Orangepill

Reputation: 24645

If there is a possibility that the firstname fields can be empty you may want to do some trims to make sure you don't insert a leading space on the last name.

   echo "<option>" . trim(trim($row['firstname']) .' '. $row['lastname']) . "</option>";

Upvotes: 1

Refugnic Eternium
Refugnic Eternium

Reputation: 4291

echo "<option>$row[firstname] $row[lastname]</option>";

Should work just fine for you. (Mind the placement of the quotes.)

Also, maybe, for later identification, you should add a 'value' tag to your option?

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174947

What's wrong with $row['firstname'] . " " . $row['lastname']...? (It's a rhetorical question. That's how you should do it).

Upvotes: 1

DeiForm
DeiForm

Reputation: 664

echo "<option>" . $row['firstname']." ".$row['lastname'] . "</option>

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 72961

You can output a literal space:

echo "<option>" . $row['firstname'] . " " . $row['lastname'] . "</option>"

Also keep in mind, you can set the value="" attribute for <option> allowing you to display any output:

echo "<option value=\" . $row['firstname'] . " " . $row['lastname'] . \">Something Different</option>"

Upvotes: 1

Related Questions