简体   繁体   中英

MySQL Show Results in line in PHP

I wan't to select data from database using mysql query and then save each value in variable so I will echo out latter Here is my PHP

  $sql = "SELECT username FROM users Order by ID Desc Limit 0,5"; 
 $query = mysqli_query($con, $sql);


while($row = mysqli_fetch_array($query))
  {
  $a = $row['0'];
  $b = $row['0'];
  $c = $row['0'];
  }
echo $a ."<br>" .$b ."<br>" .$c."<br>" ;

It show results like this same names

John
john
john

I want to show it like this

John
Richerd
Tony

You're overwriting your variables with each iteration leaving you with the name from the last iteration only. You should capture the names in an array and then display them when you have captured all of them. implode() makes adding <br> tags easy.

$users = array();
while($row = mysqli_fetch_array($query)) {
    $users[] = $row['0'];
}
echo implode('<br>', $users) . '<br>';

The $row variable will be updated only once per iteration.

$sql = "SELECT username FROM users Order by ID Desc Limit 0,5"; 
$query = mysqli_query($con, $sql);


while($row = mysqli_fetch_array($query))
{
    echo $row['0']."<br>";
}

Note that this variant adds an additional <br> tag at the end. Thus, as proposed in the other answers, the implode() function would be a better way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM