note 71793 added to function.mysql-query

From: Date: Sat, 16 Dec 2006 02:26:22 +0000
Subject: note 71793 added to function.mysql-query
Groups: php.notes 
Request: Send a blank email to php-notes+get-120648@lists.php.net to get a copy of this message
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. ---- Server IP: 216.194.113.175 Probable Submitter: 67.72.69.230 ---- Manual Page -- http://www.php.net/manual/en/function.mysql-query.php Edit -- https://master.php.net/note/edit/71793 Del: integrated -- https://master.php.net/note/delete/71793/integrated Del: useless -- https://master.php.net/note/delete/71793/useless Del: bad code -- https://master.php.net/note/delete/71793/bad+code Del: spam -- https://master.php.net/note/delete/71793/spam Del: non-english -- https://master.php.net/note/delete/71793/non-english Del: in docs -- https://master.php.net/note/delete/71793/in+docs Del: other reasons-- https://master.php.net/note/delete/71793 Reject -- https://master.php.net/note/reject/71793 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#120648) next »