Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically populate a list function

I'm trying to automate a way to read variables from a mysql database. I have a huge amount of fields that i define like $id=$row['$id']; $ref=$row['$ref']; $name=$row['$name']; etc. inside a while($row = mysql_fetch_array($result)) loop.
Since this repeats lots of times through my code, i'm trying to define them only once.

This is what i have so far:

$ids=array('id','ref','name','address');

function vars($arr=array(),$ids) {
    $ext=array();
    foreach ($ids as $value) {
        $$value=$arr[$value];
        array_push($ext,$$value);
    }
    return $ext;
}

And this is my query:

$result = mysql_query("SELECT * FROM here");
while($row = mysql_fetch_array($result)) {
    list ($id,$ref,$name,$address) = vars($row,$ids);
    echo $id.' | '.$ref.' | '.$name.' | '.$address.'<br />';
}

So, my question is: how can i automate the vars inside the list function so they can be exactly like the array $ids (because i only want to write them once)? Sorry, my first post here... Does this make sense or am i going all the way wrong?

like image 531
norferatu Avatar asked Apr 10 '26 18:04

norferatu


1 Answers

Got it!!! So easy with PDO... No function needed!

foreach($db->query("SELECT * FROM here") as $row) {
    foreach($db->query("DESCRIBE here") as $col) { 
        $$col[0]=$row[$col[0]]; 
    }
    echo $id.' | '.$ref.' | '.$name.' | '.$address.'<br />';
}

This is exactly the answer to my question.
So sorry to bother you guys...

like image 57
norferatu Avatar answered Apr 12 '26 08:04

norferatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!