Home page / PHP Tips'n'tricks

MySQL RecordSet 2 Array

mysql_query() mysql_fetch_assoc() mysql_free() ALL IN 1

Talvolta puo' essere comodo abbreviare la sintassi per ottenere un recordset da un db mysql senza utilizzare PEAR o troiai esterni ... tanto vale i propri troiai ... :)

 

Utilizzo:

 

$dati =  mysql_get($nomeCampo,$nomeTabella,$condizione);
$dati[$nomeCampo] e' un array di dati
$dati = mysql_get( array('campo1', 'campo2'), 'tabella1,tabella2', " WHERE tabella1.id = tabella2.fkTabella1 AND tabella1.id = $id" ); 
foreach($dati['campo1'] as $k=>$val){
    echo $k . ' ' . $dati['campo1'][$k] . ' ' . $dati['campo2'][$k] . '<br />';
}

 

/**
 * @return array
 * @param $field string
 * @param $table string
 * @param $cond string
 * @desc Esegue una query e ritorna il risultato come un array
 */
function mysql_get($field,$table,$cond=""){
    if(!
is_array($field)){
        
$r = array(); $i 0;
        
$fields explode(",",$field);
        
$cfields count($fields);
        
$query "SELECT ".$field." FROM ".$table.$cond;
        
$rs mysql_query($query);
        if(!
$rs) die($query."<br>".mysql_error());
        while (
$row mysql_fetch_assoc($rs)){
            if(
$cfields>1){
                for(
$c=0$c<$cfields$c++){
                    
$r[$i] .= $row[$fields[$c]];
                    
$r[$i] .= $c<($cfields-1)?" ":"";
                }
            }else 
                
$r[$i] = $row[$field];
            
$i++;
        }
        
mysql_free_result($rs);
    }else{
        
$r = array(); $i 0;
        
$cfields count($field);
        for(
$c=0$c<$cfields$c++){ if(!isset($r[$field[$c]])) $r[$field[$c]] = array(); }
        
$query "SELECT ".implode(",",$field)." FROM ".$table.$cond;
        
$rs mysql_query($query);
        if(!
$rs) die($query."<br>".mysql_error());
        while (
$row mysql_fetch_array($rs,MYSQL_ASSOC)){
            for(
$c=0$c<$cfields$c++){
                
$r[$field[$c]][$i] = $row[$field[$c]];
            }
            
$i++;
        }
        
mysql_free_result($rs);
    }
    return 
$r;


Autore: #ffffff (10-02-2007 00:00:00)

07-01-2009 - PM 04:16