Last active
August 29, 2015 14:06
-
-
Save saaiful/0077b0620b9a7a590977 to your computer and use it in GitHub Desktop.
PDO Prepared Query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
try{ | |
date_default_timezone_set('Asia/Dhaka'); | |
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8','root','pass'); | |
} | |
catch(Exception $e){ | |
var_dump($e); // Change it With Error Text | |
die(); | |
} | |
// Insert Query WIth PDO | |
$query = $db -> prepare("INSERT INTO table (name, roll) VALUES (:name, :roll)"); | |
$query -> execute(array(':name' => 'value for name', ':roll' => 'Value For Roll')); | |
$row = $query -> rowCount(); | |
// This Insert query can be done using this style too , But I Love 1st one | |
$query = $db -> prepare("INSERT INTO table (name, roll) VALUES (?, ?)"); | |
$query -> execute(array('value for name', 'Value For Roll')); | |
$row = $query -> rowCount(); | |
// Select / Read Example | |
$query = $db -> prepare("SELECT * FROM table"); | |
$query -> execute(); | |
$data = $query -> fetch(); // Fetch only First Row | |
$data = $query -> fetchAll(); // Fetch All Rows | |
// Do What ever You want to With it | |
// Another Trick , You Don't Need to fetch | |
$query = $db -> prepare("SELECT * FROM table"); | |
$query -> execute(); | |
foreach ($query as $key => $value) | |
{ | |
# code... | |
} | |
$query = $db -> prepare("UPDATE table SET name=:name WHERE id=:id LIMIT 1"); | |
$query -> execute(array(':name' => 'name Vaue', ':id' => 'id value')); | |
$row = $query -> rowCount(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment