note 79299 added to function.PDO-query

From: Date: Tue, 20 Nov 2007 05:49:41 +0000
Subject: note 79299 added to function.PDO-query
Groups: php.notes 
Request: Send a blank email to php-notes+get-132421@lists.php.net to get a copy of this message
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 ?> ---- Server IP: 69.147.83.197 Probable Submitter: 96.12.176.23 ---- Manual Page -- http://www.php.net/manual/en/function.PDO-query.php Edit -- https://master.php.net/note/edit/79299 Del: integrated -- https://master.php.net/note/delete/79299/integrated Del: useless -- https://master.php.net/note/delete/79299/useless Del: bad code -- https://master.php.net/note/delete/79299/bad+code Del: spam -- https://master.php.net/note/delete/79299/spam Del: non-english -- https://master.php.net/note/delete/79299/non-english Del: in docs -- https://master.php.net/note/delete/79299/in+docs Del: other reasons-- https://master.php.net/note/delete/79299 Reject -- https://master.php.net/note/reject/79299 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#132421) next »