PDO class – Php Data Object.
PDO is an interface to connect to databases.
try { // Check exception error
$pdo = new PDO('mysql:host=127.0.0.1;dbname=MyDatabaseName', 'username', 'password'); //interface to connected to the databases
} catch (PDOExecption e) {
// Handel exception here
die('Could not connect.'); //give up and stop program.
// can also called die($e->getMessage());
}
Sql Query
// Prepare mysql query
$statment = $pdo->prepare('select * from MyDatabaseName');
$statment->execute(); // Execute the query
// Dump all the statement results and display them. it's also display index as array.
var_dump($statment->fatchAll());
// To display database results without index
$results = $statment->fatchAll(PDO::FETCH_OBJ); // Dump all the statement results.
var_dump($results);
// Display only the first item and only the description.
var_dump($resilts[0]->description);
- don’t use mysql_connect() – this is an old functions that don’t support anymore.