-1

how to get variables from column names

$sq = "select * from arts where id = :aid limit 1";
$st = $db->prepare($sq);
$st->execute([":aid" => $id]);
$row = $st->fetch();

now, instead of:

$cat = $row['cat'];
$title = $row['title'];
$subtitle = $row['subtitle'];
... so on

I need something like:

foreach($column_name as $el){
    $var_name = $el;
}
qadenza
  • 9,025
  • 18
  • 73
  • 126

1 Answers1

1

There's rarely a good reason to do this, just use the array. However, you can use variable variables from the keys if there is only one row as you show:

foreach($row as $key => $val){
    $$key = $val;
}

There is also extract() but may be even worse practice.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • thansk a lot. If I have a lot of columns - the code is much shorter - a good reason - isn't it? – qadenza Aug 12 '21 at 16:20
  • @qadenza In general, variable variables are not very useful. How will the rest of the code use the variables if it doesn't know what the column names are? – Barmar Aug 12 '21 at 16:21
  • @Barmar - of course I know the column names - this is a table for a blog - so - `id, date, title, subtitle...` as usual – qadenza Aug 12 '21 at 16:23