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?
- Use by many databases : PDO use by numbers of database system supported by PHP.
- OOPS : PDO use object-oriented methodology.
- Write one run anywhere : Using PDO just write one code and run anywhere means you don’t need to write code for each database.
- 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.
9 Replies to “PHP PDO Insert Data Into Database”
the form is complete
VALUES (‘”.$_POST[“stu_name”].”‘,'”.$_POST[“stu_email”].”‘,'”.$_POST[“stu_city”].”‘)”;
post values have to be in single quotes to work in my database. 🙂 Great tutorial. I’m just learning PDO so this really helps. I like your form program also. Nice work.
Very nice tutorial. Keep it up! 5/5
Clear and easy to understand Tutorial!!!
Nice Work… Keep it up (Y)
Why is it that php tutorials demonstrate rather than teach. You have produced a demonstration, not a tutorial. A demonstration can get away with a statement like “Here we are using PDO Object-Oriented method to Open a Connection to MySQL” which is wrong. What you are demonstrating is “Creating an instance of a PDO object which connects to a MySQL database”.
This is only of use to someone who wants to copy code and use as is or with minimal modification. It does not teach any aspect of the PDO object usage.
It gives no insight into using PDO in a web app using multiple tables with one to many, many to many and many to one mapping, or how to implement with a table with 20 or more columns.
Dangerous tutorial. User provided data should be passed to SQL via prepared statements, with bound values.
Thank you for your script.. Honestly.. I couldn’t figure out why it would not work when I added text with an apostrophe like hadn’t or didn’t.. Then I finally figured out that you need to prepare the pdo inserts and what a task that was trying to find a tutorial on how to do that! I spent hours on it! I wish I’d read the other comments 1st before I started trying to build something using your add portion of the script.
Very clear explanation and code. Thank you.
Have you ever considered creating an ebook or guest authoring on other sites?
I have a blog based on the same topics you discuss and would really like to have you share some stories/information. I know
my viewers would appreciate your work. If you are even remotely
interested, feel free to send me an email.