简体   繁体   中英

How to echo all names of a column in all rows in php

I have a remote mysql database and a table with several rows. I want to echo one specific column (attribute) name in all rows.

Below is the php code:

<?php
  require "conn.php";
  $command = $_POST['command'];
  $mysql_qry = "select name from college_data;";
  $result = mysqli_query($conn, $mysql_qry);
  $result_details=mysqli_fetch_assoc($result);

  if(mysqli_num_rows($result) > 0) {
     echo $result_details[0].$result_details[1]." Listall successfully!"; // how to change this line of code
}
  else {
      echo " Listall fails!";
  }
?>

More specifically, how to display all the data stored in result_details?

Your code is a mess

if(mysqli_num_rows($result) > 0) {
     echo $result_details[0].$result_details[1]." Listall successfully!"; // how to change this line of code
}

You're fetching only one column. And you're not looping over the result set. Finally, you're fetching an associative array but using numeric keys

So let's clean this up

while($result_details = mysqli_fetch_assoc($result)) {
     echo $result_details['name'] . '<br>';
}

So now we're iterating over your full result set. We're using associative keys as well.

Change the code inside the if statement to:

foreach($result_details as $row){
  if(is_array($row)){
    foreach($row as $row2){
      echo $row2 . '<br/>';
    }
  }else{
    echo $row . '<br/>';
  } 
} 

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