How php echoes individual column values ​​of a row of a result from a mysql query?

Below code works fine and gives me "id", "firstname" and "lastname". I want to use a loop to repeat all the field values ​​in the result row without specifying each column name, e.g.

$row["id"]

below is the working code

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

 // Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . 
$row["lastname"] . "<br>";
}
} else {
echo "0 results";
}

$conn->close();
?> 

any thoughts please

+4
source share
3 answers

That should work.

while($row = $result->fetch_array()) {
  $i=0;
  while($i<count($row)){
    echo $row[$i];
    $i++;
  }  
}
+1
source

just use a loop foreachinside like this

foreach($row as $key=>$value){
 echo "<br> $key: ". $value. "<br>";
}
+1
source

, , ( , ).

, :

if ($result->num_rows > 0) {
    foreach($result->fetch_assoc() as $row) { // browse each records
        foreach($row as $col => $value) { // browse each columns on a record
            echo "<br>$col: $value<br>";
        }
    }
} 
else {
    echo "no result";
}
0

Source: https://habr.com/ru/post/1684193/


All Articles