Php PDO: Prepare Statement with Insert and Update

Insert data in books table using Php PDO.
The example below will insert title "Php Pamplates" and author "Kishor" in books table.

Example: Insert query with PDO prepare statement

<?php
       // configuration variables
        $dbhost     = "localhost";
        $dbname     = "mydatabase";
        $dbuser     = "root";
        $dbpass     = "";        
        // database connection
        $connection = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
         
        // new data
        $title = 'Php Pamplates';
        $author = 'Kishor';
        $sql = "INSERT INTO books (title,author) VALUES (:title,:author)";
        $query = $connection->prepare($sql);
        $query->execute(array(':author'=>$author,':title'=>$title));
?>

Now, Update data in books table using Php PDO.
The example below will update title to "Php Books" and author to "Hiren" in books table where id
is 1.

Example: Update query with PDO prepare statement

<?php
        // configuration variables
        $dbhost     = "localhost";
        $dbname     = "mydatabase";
        $dbuser     = "root";
        $dbpass     = "";        
        // database connection
        $connection = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
        // data to be updated in id 1
        $title = 'Php Books';
        $author = 'Hiren';
        $id = 1;
        // query
        $sql = "UPDATE books SET title=?, author=? WHERE id=?";
        $query = $connection->prepare($sql);
        $query->execute(array($title,$author,$id));
         
?>       

4 comments:

Anonymous said...

Very useful Example for me.
Thanks

Zilabazar said...

Gurgaon Online Advertise
online ads Gurgaon,free advertising Gurgaon,Gurgaon classifieds,local classifieds Gurgaon,online classified ads Gurgaon,flats in Gurgaon,flats sell and rent Gurgaon,free classified ads in india, Sell any things online on ZilaBazaar,paid internet advertising Gurgaon,local internet advertising Gurgaon,sell or rent car online Gurgaon,flats in Gurgaon

jvimala said...

You making it very simple and easy, Thank you
Regards,
PHP Training in Chennai | PHP Course in Chennai

Kamila said...

Thanks for sharing this post,your blog is so helpful for my studies..keep on blogging
Dot Net Training in Chennai
Software Testing Training in Chennai
Java Training Institute in Chennai
PHP Course in Chennai