Basic PHP PDO Extension Usage & Syntax

PDO Extension defines a consistent interface for accessing databases in PHP.

What does that mean? Well, it means programmers can write PHP codes which can be easily ported from one database type to another; let’s say you write your codes for MS SQL but then suddenly the project takes a turn and you need to adapt your codes for MySQL … would be great to be able to make the transition easy, wouldn’t be?

Now, you can read all about it on the Official PHP Manual and also you can read tutorials about it, but I’m about to give you below a simple example of the basic PDO Syntax.

$db = new PDO(
	'mysql:host = localhost; dbname=someDbName; charset=utf8', 

	$res = $db->query('err');
catch(PDOException $ex){
	echo "error";

//other code examples:
$stmt = $db->query('select * from table');
$results = $stmt-?fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();

//here's how to get the ID of the last inserted row
//when you're doing an insert before
$lastId = $db->lastInsertId();

//preparing queries
$stmt = $db->prepare("select * from table where id=:id and name=:name");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Leave a Reply

Your email address will not be published. All fields are mandatory.

This site uses Akismet to reduce spam. Learn how your comment data is processed.