2

I am attempting to echo a sting containing a variable already stored in a variable. Essentially I am building a class that can dynamically build tables based on a changing number of columns. I need get my db field names into the foreach loop before the foreach loop that has my db results, and then iterate over them in the loop. The problem is I have to store them in a loop prior to the db results loop; which is not recognizing it as a variable and just giving me a plain text '$row['myVar']'.

How can I get this to recognize the variable in the second loop?

$sqlVarNames = explode(', ', $sqlVar);
foreach ($sqlVarNames as $columnVar) {
    $finalColumnVars .= '<td>\'. $row[\''.$columnVar.'\'] .\'</td>';
}

and then into my second loop

foreach ($sqlResult as $row) {
    echo '<tr>';
    echo $finalColumnVars;
    echo '</tr>';
} 

I tried all sorts of escape sequences on my $finalColumnVars and can't seem to get it to output the variable instead on plain text.

Here is what I get with the above code

<td>'. $row['client_name'] .'</td>

Is this possible?

5
  • 1
    try this '<td>'. $row[$columnVar] .'</td>' Commented Aug 27, 2014 at 3:57
  • This returns '<td></td>'. I'm guessing because $row isn't anything in the first loop. Commented Aug 27, 2014 at 4:01
  • seems like you want to parse/execute/substitute php code from a string. perhaps some string substitution can help you here. Commented Aug 27, 2014 at 4:03
  • '<td>'. $columnVar.'</td>' will be ok here. Because $row is defined nowhere. Commented Aug 27, 2014 at 4:05
  • $columnVar is the db field name that needs to go in $row['$columnVar']. '<td>'. $columnVar.'</td>' would just output the field name and not it's contents. Commented Aug 27, 2014 at 4:07

2 Answers 2

4
$sqlVarNames = explode(', ', $sqlVar);
foreach ($sqlVarNames as $columnVar) {
    $finalColumnVars .= '<td>'.$row[$columnVar].'</td>';
}
Sign up to request clarification or add additional context in comments.

2 Comments

This returns '<td></td>'. I'm guessing because $row isn't anything in the first loop.
Ya you have to wrap the one foreach inside the other foreach
1

here is how you can merge these two loop and get the desired.

$sqlVarNames = explode(', ', $sqlVar);
foreach ($sqlResult as $row) {
    echo '<tr>';
    foreach ($sqlVarNames as $columnVar) {
        echo '<td>'. $row[$columnVar] .'</td>';
    }
    echo '</tr>';
} 

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.