PHP function DB query

A simple little function to make querying databases a bit less repetative


function sqlGetQuery($table,$return='q',$id=0,$select='*',$where=''){
global $dbL;
$q = mysql_query("SELECT * FROM $table WHERE 0",$dbL); $idName = mysql_field_name($q,0);
if($id>0){ $where = "$idName='$id' ".$where; }else{ $where = "$idName>0 "; }
$q = mysql_query("SELECT $select FROM $table WHERE $where",$dbL);

$selCount=explode(',',$select);$selCount=count($selCount);

if(mysql_num_rows($q)==0){
return false;
}elseif($return=='q' || mysql_num_rows($q)>1){
return $q;
}elseif($return=='r' || $selCount>1 || $select=='*'){
return(mysql_fetch_array($q));
}elseif($return=='i'){
$r=mysql_fetch_array($q);
return $r[$select];
}
}

Usage


if($q=sqlGetQuery('content_menus')){
$r=mysql_fetch_array($q);
echo 'Fetched query result: '.$r['menu_title'];
}else{
echo 'Q: no result';
}

if($r=sqlGetQuery('content_menus','r',2)){
echo 'Fetched row: '.$r['menu_title'];
}else{
echo 'R: no result';
}

if($menu_title=sqlGetQuery('content_menus','i',3,'menu_title')){
echo 'Fetched: '.$menu_title;
}else{
echo 'I: no result';
}

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word