PHP Data Objects ,PDO is a PHP extension to use PHP’S database connections. It is a consistent way to access databases. Using PDO we can make a code for different types of database and platform as well.

Why PDO  use?

  1. Use by many databases : PDO use by numbers of database system supported by PHP.
  2. OOPS : PDO use object-oriented methodology.
  3. Write one run anywhere  : Using PDO just write one code and run anywhere means you don’t need to write code for each database.
  4. Speed : PDO written in compiled language so speed is good.

Databases does PDO support :

  • MYSQL (http://www.mysql.com/): MySQL 3.x/4.0
  • OCI (http://www.oracle.com): Oracle Call Interface
  • PGSQL (http://www.postgresql.org/): PostgreSQL
  • SQLITE (http://sqlite.org/): SQLite 3.x
  • INFORMIX – IBM Informix Dynamic Server
  • IBM (IBM DB2)
  • Firebird (http://firebird.sourceforge.net/): Firebird/Interbase 6
  • DBLIB: FreeTDS / Microsoft SQL Server / Sybase

All of these drivers are not necessarily available on your system, way to find out which drivers you have:

<?php  print_r(PDO::getAvailableDrivers());?>

In this tutorial we are going to explain how we can use PDO for mysql. In this tutorial we are demonstrate how we can insert data on database using PDO.

Connection to MySQL Using PDO.

Here we are using  PDO Object-Oriented method to Open a Connection to MySQL.

Syntax :

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
//Creating connection for mysql
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

You can also refer our live demo or download the Script file. Extract the downloaded files, save it in your local server and run it using given path 

http://localhost/pdo/index.php


 My SQL code segment

To create database and table, execute following codes in your My SQL.

//First create database
CREATE DATABASE 'college';
//Then create table
CREATE TABLE 'students' (
 'student_id' int(11) NOT NULL AUTO_INCREMENT,
 'student_name' varchar(255) NOT NULL,
'student_email' varchar(255) NOT NULL,
'student_city' varchar(255) NOT NULL,
PRIMARY KEY ('student_id')
)

PHP File : index.php

Copy the below code in your file and save as view.php

<html>
<head>
<title>insert data in database using PDO(php data object)</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

<div id="main">
<h1>Insert data into database using PDO</h1>
<div id="login">
<h2>Student's Form</h2>
<hr/>
<form action="" method="post">
<label>Student Name :</label>
<input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Student Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="[email protected]"/><br/><br />
<label>Student City :</label>
<input type="text" name="stu_city" id="city" required="required" placeholder="Please Enter Your City"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
<!-- Right side div -->
<div id="formget">
<a href=https://www.formget.com/app><img src="formget.jpg" alt="Online Form Builder"/></a>
</div>

</div>
<?php
if(isset($_POST["submit"])){
$hostname='localhost';
$username='root';
$password='';

try {
$dbh = new PDO("mysql:host=$hostname;dbname=college",$username,$password);

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO students (student_name, student_email, student_city)
VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";
if ($dbh->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}

$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}

}
?>
</body>
</html>

CSS File : style.css

Styling HTML Elements.


@import url(http://fonts.googleapis.com/css?family=Raleway);

#main{
width:960px;
margin:50px auto;
font-family: 'Raleway', sans-serif;
}

h2{
background-color: #FEFFED;
text-align:center;
border-radius: 10px 10px 0 0;
margin: -10px -40px;
padding: 15px;
}

hr{
border:0;
border-bottom:1px solid #ccc;
margin: 10px -40px;
margin-bottom: 30px;
}

#login{
width:300px;
float: left;
border-radius: 10px;
font-family:raleway;
border: 2px solid #ccc;
padding: 10px 40px 25px;
margin-top: 70px;
}

input[type=text],input[type=email]{
width:99.5%;
padding: 10px;
margin-top: 8px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 16px;
font-family:raleway;
}

input[type=submit]{
width: 100%;
background-color:#FFBC00;
color: white;
border: 2px solid #FFCB00;
padding: 10px;
font-size:20px;
cursor:pointer;
border-radius: 5px;
margin-bottom: -12px;
}

#formget{
float:right;
}
h1 {
margin-left: -85px;
}

Conclusion:

So, this was all about accessing database server using php data object PDO.Hope you might have understood it properly, keep reading our other blogs posts for more coding tricks.