0

Lets say I have a mysql query:

$qry = "SELECT name,date,id,size from table";
$stmt = $db->query($qry);
while($r = $stmt->fetch()){
      foreach ($r as $k => $v){
          $$k = $v;
      }
}

This makes sense and works fine. It gives me variables such as:

    $name = 'someVal';
    $date = 'someOtherVal';

Let's say now I want to do another query that may have fields that overlap. I want to prepend a "t_" to the variable name given the same format.

$qry = "SELECT name,occupation,date from otherTable";
$stmt = $db->query($qry);
while($r = $stmt->fetch()){
      foreach ($r as $k => $v){
          $$k = $v;
      }
}

How can i have it so this query's results give me varaible names with an prepended "t_";

 $t_name = 'someVal';
 $t_occupation = 'someOtherVal';
3
  • $kk in your first example must be $$k, same in third code block Commented Feb 4, 2017 at 8:43
  • edited. thank you for pointing that out. Commented Feb 4, 2017 at 8:43
  • 1
    again in third block Commented Feb 4, 2017 at 8:44

2 Answers 2

2
 $qry = "SELECT name,occupation,date from otherTable";
 $stmt = $db->query($qry);
 while($r = $stmt->fetch()){
    foreach ($r as $k => $v){
        $varname = "t_".$k;
        $$varname = $v;
    }
 }
Sign up to request clarification or add additional context in comments.

Comments

0

just change

$$k = $v;

for

$$("t_".$k) = $v;

It will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.