Wireless Army
This is a blog / tips and tricks website for web developers and security researchers.
follow us in feedly


pdo api - connect to database
by admin
 at 2015-12-18 13:15:00.

this is a tutorial for transition from normal mysql query to pdo. Because pdo has been proven more secure
this is your normal mysql connection. config.php

<?php
//a fonction called data connect
function dataConnect() {
//connects to mysql with the fallowing credentials or display an error if info in not correct
mysql_connect("localhost", "root", "pass") or die(mysql_error());
//select the database called test or display the error of not finding the database
mysql_select_db("test") or die(mysql_error());
}
//a variable that connects to mysql database
$dbh = dataConnect();
?>

now in pdo

<?php
  //the server and the database name
  $dsn = 'mysql:host=localhost;dbname=test';
  //the username and pass
  $username = 'root';
  $password = 'pass';
  //set the characters in utf-8
  $options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
  ); 
  //a variable that connects to mysql database
  $dbh = new PDO($dsn, $username, $password, $options);
?>

but if we use just this code, it and there is an error, nothing will happen so we use try and catch to display the error like so:

<?php
try {
  //the server and the database name 
  $dsn = 'mysql:host=localhost;dbname=test';
  //the username and password 
  $username = 'root';
  $password = 'pass';
  //set the characters in utf-8
  $options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
  ); 
  //a variable that connects to mysql database 
  $dbh = new PDO($dsn, $username, $password, $options);
 //in some cases that nothing happens this line will give (throw) you the error if you use try catach 
  $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}
?>


now you can include the connection in files with this:

<?php require "config.php"; ?>


and close it with this

<? $dbh = null; ?>