Skip to content

Instantly share code, notes, and snippets.

@varemenos
Created March 29, 2012 15:51
Show Gist options
  • Save varemenos/2238845 to your computer and use it in GitHub Desktop.
Save varemenos/2238845 to your computer and use it in GitHub Desktop.
PHP - Database connection and query
<?php
// db info
$db_host = 'localhost'; // local only connection
$db_port = 3306; // default mysql port
$db_database = 'db_user'; // database username
// initiate dns string
$dns = "mysql:host=$db_host;port=$db_port;dbname=$db_database";
// create database object or close connection
try{
$db = new PDO(
// Database Information
$dns,
// Database User Information
'db_name',
// Database User Password
'db_pass',
// set collation to utf8
// without this, PHP cant display greek characters properly
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
);
}catch(PDOException $e){
print '<h4>' . $e->getMessage() . '</h4>';
}
// once you have your database object, unset database connection info
unset(
$db_host,
$db_port,
$db_database,
$dns
);
// prepare query
$statement = $db->prepare("SELECT * FROM table WHERE id= ?");
// execute query
$statement->execute(array($id));
// 1 result per time
while($result = $statement->fetchObject()){
}
// or
// all results at once
$results = $statement->fetchAll();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment