Algemeen en interessant nieuws over en door NosTech

NIEUWS

Associate fields to table in MySQL using PHP Just a...
08-12-2008 19:06

Associate fields to table in MySQL using PHP

Just a fairly useful (to me at least!) “implementation” of mysql_fetch_assoc to stop the clobbering of identical column names and allow you to work out which table produced which result column when using a JOIN (or simple multiple-table) SQL query: (assuming a live connection …)

$sql = “SELECT a.*, b.* from table1 a, table2 b WHERE a.id=b.id”; // example sql
$r = mysql_query($sql,$conn);
if (!$r) die(mysql_error());
$numfields = mysql_num_fields($r);
$tfields = Array();
for ($i=0;$i<$numfields;$i++)
{
    $field =  mysql_fetch_field($r,$i);
    $tfields[$i] = $field->table.’.’.$field->name;
}
while ($row = mysql_fetch_row($r))
{
    $rowAssoc = Array();
    for ($i=0;$i<$numfields;$i++)
    {
        $rowAssoc[$tfields[$i]] = $row[$i];
    }
//    do stuff with $rowAssoc as if it was $rowAssoc = mysql_fetch_assoc($r) you had used, but with table. prefixes
}

< Alle nieuws