Reputation: 2777
PDO sql codes :
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$gg = join('</td><td>', $r);
echo "<tr><td>" . $no_count . "</td><td>" . $gg . "</td></tr>";
$no_count = $no_count + 1;
}
variable $r
is the record, how can I echo the field name of $r
?
Let's say $r
carry records from 2 different fields "product" and "price". The value of $r
is "apple", "130". How can I add "usd" into "130"?
I need something like.... if $field_name == "$r['price']" { $r = join('usd', $r); };
Thanks to Mike B, I almost there :
while($r = $q->fetch(PDO::FETCH_ASSOC)){
foreach ($r as $name => $value) {
if ($name == "price"){
$r = "usd" . $value; // this line got problem, how to change the value in an array variable $r?
}
}
$gg = join('</td><td>', $r);
echo "<tr><td>" . $no_count . "</td><td>" . $gg . "</td></tr>";
$no_count = $no_count + 1;
}
Upvotes: 1
Views: 126
Reputation: 32145
array_keys($r)
will get you a list of fields from the table since you're fetching an associative array.
You can also loop through $r
:
foreach ($r as $name => $value) {
print "$name: " . $value;
}
// this line got problem, how to change the value in an array variable $r?
$r[$name] = 'usd' . $value;
Make the edit to the original name. Since you have the key in the $name
variable from the foreach loop you can set it directly.
Upvotes: 3