# MySQL Connect & Close : Till 5
<?php
$mysqlObj = mysql_connect('localhost' , 'mysql_user' , 'password');
if(!$mysqlObj) {
die('[' . mysql_errorno() . ']Could not connect to the DB : ' . mysql_error());
}
mysql_close($mysqlObj);
?>
# MySqli Connect & Close : > 5
<?php
$mysqli = new mysqli('localhost' , 'user' , 'password' , 'database');
if($mysqli->connect_errno) {
echo 'Failed to connect to Mysql : (' . $mysql->connect_errno . ' )' . $mysql->connect_error;
}
?>
// MySQL connection $db = new PDO(‘mysql:host=localhost;dbname=testdb’, $login, $passwd); // PostgreSQL $db = new PDO(‘pgsql:host=localhost port=5432 dbname=testdb user=john password=mypass’); // SQLite $db = new PDO(‘sqlite:/path/to/database_file’);
// Handling Exceptions
<?php
try { $db = new PDO(…); } catch (PDOException $e) { echo $e->getMessage(); }
?>
<?php
//Passing an argument for creating Persistent Connection.
$opt = array(PDO::ATTR_PERSISTENT => TRUE) ; try { $db = new PDO(“dsn”, $l, $p, $opt); } catch (PDOException $e) { echo $e->getMessage(); }
?>
# Insert
<?php
$title = 'PHP Securities';
$author = "Rasmus Leodorf";
$sql = "INSERT INTO books (title,author) VALUES (:title,:author)";
$q = $db->prepare($sql);
$q->execute(array(':author' => $author , ':title' => $title));
?>
# Update
<?php
$title = 'PHP Pattern'; $author = 'Someone'; $id = 3;
$query = 'UPDATE books SET title=? , author=? WHERE id=?';
$q = $db->prepare($sql);
$q->execute(array($title , $author , $id));
?>
# Fetching Data
$res = $db->query(“SELECT * FROM users”, PDO::FETCH_ASSOC);
foreach ($res as $row) { // $row == associated array representing // the row’s values. }
// Other way
$query = “SELECT * FROM users”; $res = $db->query($query)->fetchAll(PDO::FETCH_ASSOC);