Jump to content

PHP PDO Tutorial for safe database queries - IN-DEPTH


Wife

Recommended Posts

Hello,

So, because I am already being hated by many people I decided to give you something a little bit more productive this time.

1. The Basics

What is PDO?

PDO stands for PHP Data Objects which simply is a object based database library. One of the biggest advantages of PDO apart from it being very secure and light weight (when used correctly, of course) is the fact that it is a abstract level library for database methods and works pretty much widely on every well known database server. The library consists from bunch of classes containing methods and functions for database queries.

Example of usage

$statement = $connection->prepare($query);$statement->execute();
In PDO, when you are passing variables to query, they are defined AFTER preparing the query, while/or before executing it.

Example of variables in PDO query

$query = 'SELECT * FROM users WHERE username = :username'; //We use 'placeholders' :username is a placeholder$statement = $connection->prepare($query);$statement->execute(array(':username' => $username));
So, this way the variable - which can be assigned from HTTP_REQUEST or via static methods, is never passed directly to the query and helps us prevent error based SQL injection.

Fetching data, data types

//Fetching data as an array$result = $statement->fetch(PDO::FETCH_ASSOC);print_r($result);//Alternative, for looping all the results found for statementforeach($statement as $row) {echo '$row['data'];} //So here the result of $statement->execute is assigned as $row and data can be accessed using $row['datafield']; $row['datafield2'];//etc, based on your database table names.//Fetching data as object (I have to include this as we are talking about DATA OBJECTS$result = $statement->fetch(PDO::FETCH_OBJ);echo $result->username;echo $result->othervalue;//Ok so this is the object oriented method, where fetch returns an object where property names are assigned from result.
It is also possible to return all the remaining values from data set by using fetchAll(); method. Usage defined above.

You can see a complete list of PHP datatypes online.

Establishing a database connection

//Okay, this should be pretty straight forward. The connection is handled inside try{} and catch(){} blocks.try {//Variables for username and password$username = 'db_user';$password = 'db_password';//This creates a new PDO object for variable $connection. Connection details are//mysql:host, dbname, $username, $password$connection = new PDO('mysql:host=localhost;dbname=database_name', $username, $password);//Let's set the attribute errormode to pdo error mode exception for our catch() block.$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);} catch (PDOException $error) {//getMessage() us any possible errors with connecting, die(); is for killing the connection.$error->getMessage();$connection->die();}
Part 2. Coming tomorrow, and then we will be actually creating something, a dynamic database SET query using USER_AGENT and then outputting the data. Edited by Facial
  • Like 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...