Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to php echo individual column values of a result row from mysql query?

Tags:

php

mysql

The below code works perfectly and gives me the "id" "firstname" and "lastname". What I want is to use a loop to echo all the field values in the result row without having to quote each column name like

$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

like image 925
Neo Avatar asked Oct 30 '22 03:10

Neo


2 Answers

This should work..

while($row = $result->fetch_array()) {
  $i=0;
  while($i<count($row)){
    echo $row[$i];
    $i++;
  }  
}
like image 108
Zedex7 Avatar answered Nov 15 '22 05:11

Zedex7


just use a foreach loop inside while like this

foreach($row as $key=>$value){
 echo "<br> $key: ". $value. "<br>";
}
like image 24
Passionate Coder Avatar answered Nov 15 '22 06:11

Passionate Coder