note 71793 deleted from function.mysql-query by philip
| From: | philip@php.net | Date: | Fri, 04 Sep 2015 19:23:35 +0000 |
| Subject: | note 71793 deleted from function.mysql-query by philip | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-203661@lists.php.net to get a copy of this message | ||
Note Submitter: noah at missionecommerce dot com
----
I got so tired of having to type out all the 11 letters in "mysql_query()" and even more
tired of having to iterate through the result set....
So I created the perfect little all purpose wrapper function, called "q()";
<?
function q($query,$assoc=1) {
$r = @mysql_query($query);
if( mysql_errno() ) {
$error = 'MYSQL ERROR #'.mysql_errno().' : <small>' . mysql_error().
'</small><br><VAR>$query</VAR>';
echo($error); return FALSE;
}
if( strtolower(substr($query,0,6)) != 'select' ) return
array(mysql_affected_rows(),mysql_insert_id());
$count = @mysql_num_rows($r);
if( !$count ) return 0;
if( $count == 1 ) {
if( $assoc ) $f = mysql_fetch_assoc($r);
else $f = mysql_fetch_row($r);
mysql_free_result($r);
if( count($f) == 1 ) {
list($key) = array_keys($f);
return $f[$key];
} else {
$all = array();
$all[] = $f;
return $all;
}
} else {
$all = array();
for( $i = 0; $i < $count; $i++ ) {
if( $assoc ) $f = mysql_fetch_assoc($r);
else $f = mysql_fetch_row($r);
$all[] = $f;
}
mysql_free_result($r);
return $all;
}
}
?>
Example:
<?
$r = q('Select id,foo FROM blah');
echo $r[0]['id']; // first row, field 'id'
// for single field single row selects
// only the value is returned
$count = q('SELECT count(*) from blah');
// $count is the number
?>
Returns affected_rows and/or insert_id for anything other than select's. If you dont want field
name keys then pass 0 for second parameter.