PHP – Get data from mySQL, a generic approach



<?php 

function GetDbConnection(){ 

  $servername = "localhost"; 
  $username = "user"; 
  $password = "password"; 
  $dbname = "myDB"; 
  $conn = new mysqli($servername, $username, $password, $dbname); 
  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  } 
  return $conn;
}

function ListAllFromQuery($conn,$sql){
      
  $mArr = array();
  $result = $conn->query($sql);
  if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
      array_push($mArr, $row);
    }
  }
  return $mArr;
}


$conn = GetDbConnection();
$list =ListAllFromQuery($conn,"SELECT * FROM tblUser ORDER BY id;");
$output="";

for($i = 0; $i < count($list); $i++) { 
  $currentUser= $list[$i]; 
  foreach($currentUser as $key => $key_value) {
    $output.= $key . " = " . $key_value;
    $output.= "<br>";
  }
  $output.= "<hr>";
}

$conn->close();

echo $output;

?>

Leave a Reply