PDO Insert


 

PDO Insert

In this tutorial we will study about insertion of data using PDO in PHP, How to insert data using inbuilt function exec() is described here. Examples will make this clearer.

In this tutorial we will study about insertion of data using PDO in PHP, How to insert data using inbuilt function exec() is described here. Examples will make this clearer.

PDO-Insert-Code

To get data from the database, we need to put some data into it. In PDO we use same conventional coding of inserting data, but to execute the query we use PDO::exec method. PDO::exec method returns the number of effected rows which are successfully updated. PDO::exec method should use when SQL statements wont return a result set. 

Example:

<?php

header('Content-type:text/plain');

try {

$db = new PDO("pgsql:dbname=ignou;host=localhost", "postgres", "1234" );

echo "connected\n";

$id=5;

$name='prabhat';

$roll=4;

$sql='insert into student(id,name,roll)values ($id,$name,$roll)';

$count=$db->exec("insert into student(id,name,roll)values ('$id','$name','$roll')");

echo "Number of affected rows are:".$count;

$db=null;

}

catch (PDOException $e)

{

echo $e->getMessage();

}

?>

Output:

connected
Number of affected rows are:1

 

Ads