Basic PDO example

from the Artful MySQL Tips List


In this code, substitute the name of the computer where the MySQL server is running for HOSTNAME, your MySQL username for USR, and your MySQL password for PWD:

<?php

try {
  
// LIST PDO DB DRIVERS ENABLED IN PHP.INI:
  
echo "Available database drivers:<br />";
  
var_dumpPDO::getavailableDrivers() );
  echo 
"<br />";
  
  
// EXAMPLE PDO QUERY: LIST USERS & HOSTS IN MYSQL.USER:
  
$pdo = new PDO"mysql:host=HOSTNAME; dbname=t"'USR''PWD' );
  
$qry "select host, user from mysql.user";
  echo 
"Results for $qry:<br />";
  foreach( 
$pdo->query$qry ) as $row print_r$row );

catch( 
PDOException $e ) {
  exit( 
"Error: " $e->getMessage() . "<br />" );
}

?>

Last updated 21 Aug 2024


Return to the Artful MySQL Tips page