note 79300 deleted from function.PDO-query by betz
| From: | betz@php.net | Date: | Tue, 20 Nov 2007 22:24:54 +0000 |
| Subject: | note 79300 deleted from function.PDO-query by betz | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-132449@lists.php.net to get a copy of this message | ||
Note Submitter: wuzup_13 at hotmail dot com
----
This is an example PDO query function, dbQuery only needs to be passed your database query in order
to work.
Our return solves the problem of not being able to count PDO returns/objects.
You can perform a count() on the return array, unless only 1 row is returned, then you will be
counting columns, instead of rows.
See for yourself, I think you'll find this useful, it solved many of our problems - we have to
do a bit more backend work, but such is the cost of a reasonable PDO function.
EXAMPLE:
// If you know the select statement will return only one row:
$row = dbQuery("SELECT * FROM users WHERE user_id = 1");
print $row['user_id']; // Prints one row. If more than one, will print "Array"
// If you are expecting one or more rows:
$query = dbQuery("SELECT * FROM users");
foreach ($query as $row) {
print $row['user_id']; // Prints ALL rows
}
<?php
function dbConnect() {
global $dbh;
$dbInfo['database_target'] = "localhost";
$dbInfo['database_name'] = "my_db";
$dbInfo['username'] = "root";
$dbInfo['password'] = "";
$dbConnString = "mysql:host=" . $dbInfo['database_target'] . ";
dbname=" . $dbInfo['database_name'];
$dbh = new PDO($dbConnString, $dbInfo['username'], $dbInfo['password']);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$error = $dbh->errorInfo();
if($error[0] != "") {
print "<p>DATABASE CONNECTION ERROR:</p>";
print_r($error);
}
}
function dbQuery($queryString) {
global $dbh;
$query = $dbh->query($queryString);
$i = 0;
foreach ($query as $query2) {
$queryReturn[$i] = $query2;
$i++;
}
if($i > 1) {
return $queryReturn;
} else {
return $queryReturn[0];
}
}
dbConnect(); // Connect to Database
?>