PDO Select:
We can do select query by prepared statements or direct execution as
$query = "SELECT * FROM foo";
$pq = $con->prepare($query); //Preparing Query
//Foo is Table Name
//You may use column names instead of '*' Example: select id,name,color from foo
$pg->execute(); //Executing Prepared Query
(or)
$pq = $con->query($query); //No need to be $pg->execute() here;
For retrieving data we can follow any method as before used
1)
for($i=0; $row = $pg->fetch(); $i++){
print $i." - ".$row['name']."<br/>";
print $i." - ".$row['id']." ".$row['name'];//What ever format you need
}
2)
foreach($con->query($pg) as $row) {
print $row['id'] . "\t";
print $row['name'] . "\t";
}
3)
$pg->fetch(); //For single Row
$pg->fetchAll(); //For all rows
In this we can use fetch styles they are:
PDO::FETCH_BOTH(default) //return both 0 indexed and name indexed array Example: array([0]=>php,[name]=>php);
PDO::FETCH_ASSOC //return 'name' indexed array Example: array([name]=>php);
PDO::FETCH_BOUND //returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were bound with the PDOStatement::bindColumn() method
PDO::FETCH_CLASS // returns a new instance of the requested class
PDO::FETCH_INTO // updates an existing instance of the requested class
PDO::FETCH_LAZY // creating the object variable names as they are accessed
PDO::FETCH_NAMED //returns an array with the same form as PDO::FETCH_ASSOC, except that if there are multiple columns with the same name, the value referred to by that key will be an array of all the values in the row that had that column name
PDO::FETCH_NUM //returns an array indexed by column number as returned in your result set
PDO::FETCH_OBJ // returns an anonymous object with property names that correspond to the column names returned in your result set
We mostly use first two only as
$data = $pg->fetchAll(PDO::ASSOC); (or) $data = $pg->fetch(PDO::ASSOC);
Any problem comment to me.
0 comments:
Post a Comment