For example I have an attributes table
and I can add infinite attributes. I do that with ALTER TABLE
when I add a new column and UPDATE
when I insert the value of the attribute. All these columns must be shown in a table. However I am having dificulties with showing the newly added column value.
Here is how a static column value echo would look like:
public function showAllUsers(){
$x = $this->getAllUsers();
foreach ($x as $data) {
echo '<tr>';
echo '<th>'. $data['id'].'</th>';
echo '<td>'.$data['user'].'</td>';
echo '<td>'.$data['email'].'</td>';
echo '<td>'.$data['age'].'</td>';
echo '</tr>';
}
}
It echoes the values of the database that I have specified. But I need a loop that will echo any newly added value so the static echo method above won't work.
This is what I have come up with so far:
public function showAllUsers(){
$x = $this->getAllUsers();
foreach ($x as $data) {
echo '<tr>';
print_r( '<th>'. $data.'</th>');
echo '</tr>';
}
}
And it just shows a Notice: Array to string conversion
and echoes one tag with value of 0. How do i echo all of the content from one row?
Try this:
public function showAllUsers()
{
$x = $this->getAllUsers();
echo '<tr>';
foreach (array_keys($x[0]) as $field) {
echo '<th>'. $field.'</th>';
}
echo '</tr>';
foreach ($x as $data) {
echo '<tr>';
foreach ($data as $val) {
echo '<td>'. $val.'</td>';
}
echo '</tr>';
}
}
You can implode the $data array with the html tags.
Implode takes all array values and joins them with the "glue" and makes it a string.
public function showAllUsers(){
$x = $this->getAllUsers();
foreach($x as $data){
echo "<tr>";
echo "<th>" . implode("</th><th>", $data) . "</th>";
echo "</tr>";
}
}