Reputation: 29
I have been trying to do the following: I have stored subjects in database seperated by commas to make an array. I am then running a foreach loop to get the subjects once they have been exploded. The part where i am stuck is I am trying to create variables based on the subject names to then run a mysqli code that will derive information from another table in DB Based on the subject name that i should be setting.
I've tried using eval, which does not display anything when i run the code.
$hwvar = "";
$hwsubject = "";
foreach ($hwarray as $hwvar) {
eval("$hwvar = $row".""."['$hwvar']");
}
?>
<td><?php echo $hwvar; ?></td>
so i need the loop to produce the following for each item is loops through ($sujectname is what is stored and derived from the database e.g homework1) $subjectname = $row['$subjectname'];
Upvotes: 0
Views: 96
Reputation: 94652
It would be so much simpler and safer (eval() is a dangerous function in the wrong hands) to just output the <TD>
inside the loop
foreach ($hwarray as $hwvar) {
$dat = $row[$hwvar];
echo "<td>$dat</td>";
}
?>
NOTE:
eval()
should be avoided at almost all costs, for all sorts of reasons.The simplest to understand is the distinct possibility that creating variables in the global scope dynamically has the possibility of overwriting one, or more, of your existing variables, making debugging a complete nightmare.
UPDATE, after comments
I dont have your database so I mocked up a simple example of what I assume you are doing
// dummy database result containing 2 result rows
$rows = [['home'=>'100', 'home2'=> '200'],['home'=>'300', 'home2'=> '400']];
// yoour list of required columns
$hwarray = ['home','home2'];
// loop over the query resultset
// your code might be a while loop over a fetch like
// while ($row = $result->fetch_assoc()){
// for example
foreach ($rows as $row){
foreach ($hwarray as $hwvar) {
echo "<td>$row[$hwvar]</td>";
}
}
Upvotes: 1