Saturday, June 22, 2013

Simple and Safe SELECT Statement syntax with PDO in PHP

$sql= "SELECT filmID, filmName, filmDescription, filmImage, filmPrice, filmReview FROM movies WHERE filmID = :filmID";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':filmID', $filmID, PDO::PARAM_INT);
Here's how it goes. You add your simple SELECT query to your variable changing any variable to :something.
You then prepare the query and finally bind the Parameter (the variable from the first line.)
It's that simple and your database is protected from SQL injections.

INSERT Statement with PDO and PHP syntax, made easy!

        PHP Data Objects (PDO) 
In this 
post, we will implement prepared statement for insert and update data. I
 will show simple example.

// configuration
$dbtype  = "sqlite";
$dbhost  = "localhost";
$dbname  = "test";
$dbuser  = "root";
$dbpass  = "admin";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// new data
$title = 'PHP Security';
$author = 'Jack Hijack';

// query
$sql = "INSERT INTO books (title,author) VALUES (:title,:author)";
$q = $conn->prepare($sql);

It's that easy and this query will protect your MySQL database from malicious injections.
PDO's Select syntax is simple and very powerful