PHP Data Objects (PDO) Step By Step Tutorial - Part 9: In this post, we will implement prepared statement for insert and update data. I will show simple example.
<?php
// configuration
$dbtype = "sqlite";
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "admin";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$title = 'PHP Security';
$author = 'Jack Hijack';
// query
$sql = "INSERT INTO books (title,author) VALUES (:title,:author)";
$q = $conn->prepare($sql);
$q->execute(array(':author'=>$author,
':title'=>$title));
?>
Example for update data:
<?php
// configuration
$dbtype = "sqlite";
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "admin";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$title = 'PHP Pattern';
$author = 'Imanda';
$id = 3;
// query
$sql = "UPDATE books
SET title=?, author=?
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($title,$author,$id));
?>
Previous: PDO: Positional and Named Placeholders
Next: PDO: Prepared Statement and Bound Values
| Series this article: PDO: Introduction PHP Data Object PDO: Activation PHP Data Objects Extension PDO: Connecting Use PHP Data Object PDO: Portable Connection to Database PDO: Posibble Fetch Mode PDO: Error Handling PDO: Prepared Statement PDO: Positional and Named Placeholders PDO: Insert and Update Statement Use Prepared Statement PDO: Prepared Statement and Bound Values PDO: Working With BLOBs PDO: Alternative Retrieve BLOB Data PDO: Setting Connection Attributes PDO: Error Mode Attributes PDO: Improve Performance with Persistent Connection PDO: Getting Connection Attributes advertisements blog comments powered by Disqus |

