Query retrieval and display

from the Artful MySQL Tips List


Here is how to do basic query retrieval and HTML result display with PHP using the mysqlI library, given a database name in $db and a MySQL query string in $qry. Substitute your default values for connection parameters $host, $user, $pswd:

<?php
function q2html$db$qry$host$usr$pwd  ) {  // EXECUTE QUERY, PAINT RESULT
  
$conn connect_db$db$host$usr$pwd  );
  
$res mysqli_query$conn$qry ) or exit( mysqli_error($conn) );
  
r2html$res );  
}

function 
connect_db$db
                     
$host "LOCALHOST",
                     
$user "USR"
                     
$pswd "PSWD"
                   
) {
  
$conn mysqli_connect$host$user$pswd$db ) or exit( mysqli_error() );
  print 
"<p>Connected to the $db DB</p>n";
  return 
$conn;
}

function 
r2html$res$tblformat="border='1'" ) {  // PAINT RESULT AS HTML TABLE
  
if( is_bool$res )) return $res "True" "False";
  echo 
"<table $tblformat>n<tr>";
  while( 
$f mysqli_fetch_field$res )) echo "<td><b>"$f->name"</b></td>n";
  echo 
"</tr>n";
  while( 
$row mysqli_fetch_row$res )) {
    echo 
"<tr>";
    foreach( 
$row as $c ) echo "<td>", empty($c)?"&nbsp;":$c"</td>";
    echo 
"</tr>n";
  }
  echo 
"</table>n";
}
?>


If you put that code in a page called qry.php with your default values of HOST, USR, PWD, call it like so::

<?php
require_once( "qry.php" );
q2html"test""show tables like 't%'"HOSTUSRPWD );
?>

Last updated 10 Jan 2015


Return to the Artful MySQL Tips page