Foreach associative array table - php

**Edit: We got there in the end, Thanks guys! It was the HTML tables confusing me.
<tr>
<td><?php echo $row['owner_firstname'];?></td>
<td><?php echo $row['owner_surname'];}?></td>
</tr>**
I am trying to put some information into a table and I don't want to do it using this method...
<tr>
<td><?php echo $rows[0]['owner_firstname'] ; ?></td>
<td><?php echo $rows[0]['owner_surname'] ; ?></td>
<td><?php echo $rows[0]['owner_contantno'] ; ?></td>
</tr>
I want to use a foreach loop but I am struggling to get it working, Each person from the database is [0],[1],[2] etc in my array.
Here is a print_r of my dataset
Array
(
[0] => Array
(
[ID] => LEI12345
[owner_firstname] => Shanel
[owner_surname] => **********
[owner_contantno] => *******
[owner_address] => ********
[band_firstname] => Nathan
[band_lastname] => **********
[band_disability] => *******
[band_emergencycontact] => ********
[band_description] => ************
)
)

$data = $yourDataSet; // your data set here
// check data
if($data) {
foreach($data as $val) {
$str = "";
$str = "<tr>";
$str .= "<td>" . $val['owner_firstname'] . "</td>";
$str .= "<td>" . $val['owner_surname'] . "</td>";
// add other td here if there's more
// end of tr
$str .= "</tr>";
echo $str;
}
}
try this one, i hope this one would help

from your for each you can grab results like this
get your results to an array
$rows = mysql_fetch_array($query);
foreach($rows as $key=> $row){
if(is_array($row))
foreach($row as $id => $val)
echo '<td>'.$val.'</td>';
}

Related

PHP Display Array in HTML table

I have the database and web server on separate machines, an array from a mysql query is passed to the web server and looks like so
Array (
[user_id] => 1
[username] => phillip
[password] => 12345
[email] => phillip#gmail.com
[account_balance] => 100 )
If I print out this array in PHP using print_r($myArray); it shows in the web browser like so
Array ( [user_id] => 1 [username] => phillip [password] => 12345 [email] => phillip#gmail.com [account_balance] => 100 )
I want to create PHP code that will iterate this array and make columns for user_id, username, password, email, and account_balance and then display the results in rows.
Here is my PHP code in a file display.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Page</title>
</head>
<body>
<table border="1">
<?php
include(fileThatCallsDBServer.php);
$myArray = getMYSQLArray(); //This calls a function located in the file in the include() and returns array
print_r($myArray); //print the array for testing purposes
//Create table to display array
$html = "<table>";
foreach($myArray as $row) {
$html .= "<tr>";
foreach ($row as $cell) {
$html .= "<td>" . $cell . "</td>";
}
$html .= "</tr>";
}
$html .= "</table>";
?>
</body>
</html>
However, nothing gets displayed when I look at the page on my browser. Ideas?
You need to display keys and their respective values.
So, in array loop, get keys along with values.
You do not need two foreach loops.
...
foreach($myArray as $key => $row) {
$html .= "<tr>";
$html .= "<td>" . $key . ': ' . $row . "</td>";
$html .= "</tr>";
}
...
Your code looks fine, you just seem to forget to echo the final result of your $html variable.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Page</title>
</head>
<body>
<table border="1">
<?php
include(fileThatCallsDBServer.php);
$myArray = getMYSQLArray(); //This calls a function located in the file in the include() and returns array
print_r($myArray); //print the array for testing purposes
//Create table to display array
$html = "<table>";
foreach($myArray as $row) {
$html .= "<tr>";
foreach ($row as $cell) {
$html .= "<td>" . $cell . "</td>";
}
$html .= "</tr>";
}
$html .= "</table>";
?>
echo $html;
</body>
</html>
<?php
$data = Array ( 'user_id' => 1,'username' => 'phillip', 'password' => 12345, 'email' => 'phillip#gmail.com','account_balance' => 100 );
$keys = array_keys($data);
?>
<table border=1>
<tr>
<?php
foreach($keys as $key=>$value):
?>
<td><?php echo $value;?></td>
<?php
endforeach;
?>
</tr>
<tr>
<?php
foreach($data as $key=>$value):
?>
<td><?php echo $value;?></td>
<?php
endforeach;
?>
</tr>
</table>
Hi your array is not nested array so you just have to echo it:
echo "<tr><td>".$myArray['user_id']."</td>
<td>".$myArray['username']."</td>
<td>".$myArray['password']."</td>
<td>".$myArray['email']."</td>
<td>".$myArray['account_balance']."<td></tr>";

mysqli_fetch_array using a foreach loop

Ive got a pretty basic table named 'customers' with four columns:
ID (primary Auto Increment)
businessName
contactName
contactEmail
I call it with:
$result = mysqli_query($con, "SELECT * FROM customers");
and was using mysqli_fetch_array to display it on the page with a foreach loop:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "<td><a href='updateform.php?id=" . $row['id'] . "'>Edit</a></td>";
echo "</tr>";
}
Which gives you an array like:
Array ( [id] => 1 [businessName] => Microsoft [contactName] => Bill Gates [contactEmail] => bill#microsoft.com ) Array ( [id] => 2 [businessName] => Amazon [contactName] => Jeff Bezos [contactEmail] => jeff#amazon.com )
Is it possible to display results differently based on which column (technically now position in the array) they are in? I would like to make a
a href="mailto:bill#microsoft.com"
link when it gets to contactEmail.
What if I wanted to display just one key or value instead of using foreach?
It doesn't seem possible to call
$row['contactEmail']
in the foreach loop
which confuses me since below that I am able to create a link to
$row['id']
If anyone has any ideas how to do this, or if there is a better way to be displaying this information, I'm open to suggestions, as I'm not very good at programming, especially PHP.
Yes! you can just add like this:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<tr>";
foreach ($row as $key => $value) {
if($key == "contactEmail"){
$mailUrl = "mailto:".$value;
echo "<td>".$value."";
}
else{
echo "<td>" . $value . "</td>";
}
}
echo "<td><a href='updateform.php?id=" . $row['id'] . "'>Edit</a></td>";
echo "</tr>";
}
Yes, You can able to mysqli_fetch_array retrieve data directly using foreach loop. like bellow :
<?php
$result = mysqli_query($con, "SELECT * FROM customers");
?>
<table>
<tr>
<td>Business Name</td>
<td>Contact Name</td>
<td>#</td>
</tr>
<?php
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<tr>";
echo "<td>".$row['businessName']."</td>";
foreach ($row as $key => $value) {
$newValue = $key == "contactEmail" ? ''.$value.'' : $value;
echo "<td>" . $newValue . "</td>";
}
echo "<td><a href='updateform.php?id=" . $row['id'] . "'>Edit</a></td>";
echo "</tr>";
}
?>
</table>

how to take foreach result in a table format

I want to take the result of foreach in a table format and that whole table in a variable.
Here is my model:
public function cron_job_seller(){
$this->db->select('*');
$this->db->from('wc_seller_products');
$query = $this->db->get();
$result = array();
foreach ($query->result() as $row){
$result[] = $row;
}
return $result;
}
and my controller is
public function cron_job(){
$this->load->model('home/Home_model');
$buyer = $this->Home_model->cron_job_buyer();
$this->load->library('email', array('mailtype'=>'html'));
$seller = $this->Home_model->cron_job_seller();
echo "<table>";
foreach($seller as $key=>$row) {
echo "<tr>";
foreach($row as $key2=>$row2){
echo "<td>" . $row2 . "</td>";
}
echo "</tr>";
}
echo "</table>";
gives o/p like this in table format
19 102 Rolex 65 Good 0000-00-00 fh ghf fgh ghf ghf gfh ghf ghf 56 56 download14.jpg 11/6/2016 19:03 2016-07-15 12:13:35 1 0
when i print $seller variable it gives
Array ( [0] => stdClass Object ( [id] => 19 [seller_id] => 102 [brand_name] => Rolex [model_no] => 65 [condition] => Good [date_purchase] => 0000-00-00 [case_size] => fh [case_shape] => ghf [case_material] => fgh [strap_type] => ghf [dial_colour] => ghf [water_resistance] => gfh [local_overseas] => ghf [warranty_period] => ghf [min_price] => 56 [sale_price] => 56 [photo] => download14.jpg [date] => 11/6/2016 19:03 [time] => 2016-07-15 12:13:35 [status] => 1 [login] => 0 [verified] => )
now i want 2 things in this:
1. that whole table in a single variable.
2. array keys like id, seller_id,brand_name as table heading
i really got confused what to do now and how to do...please help
public function cron_job() {
$this->load->model('home/Home_model');
$buyer = $this->Home_model->cron_job_buyer();
$this->load->library('email', array('mailtype'=>'html'));
$seller = $this->Home_model->cron_job_seller();
$theader = '';
$tbody = "<tbody>";
foreach($seller as $key => $row) {
$tbody .= "<tr>";
foreach($row as $key2 => $row2){
if (!$theader) {
$theader = array_keys($row2);
}
$tbody .= "<td>" . $row2 . "</td>";
}
$tbody .= "</tr>";
}
$tbody .= "</tbody>";
if (!empty($theader)) {
$theader = '<thead><th>' . implode('</th><th>', $theader) . '</th></thead>';
}
$table = '<table>'.$theader.$tbody.'</table>';
}
you don't need to worry much about it... It could be a solution. Just do like this in your controller:
$seller = $this->Home_model->cron_job_seller();
$table = "<table border='1'>";
$i=1;
foreach($seller as $key=>$row) { //you don't need to loop twice
if($i == 1){
$table.="<tr>";
$table .= "<th>".$key."</th>";
$table.="</tr>";
$i=0; //change value of $i so for next iteration the header will not print
}
$table .= "<tr>";
$table .= "<td>" . $row . "</td>";
$table.= "</tr>";
}
$table .= "</table>";
and also you need to return $query->result() from your model.
and now try print $table
using echo $table; it will print result as you want and now it is also set in a single variable so you can, and you set to $data['table'] = $table and end it to view, if you need.
You can just loop through the Array of Data from the DB and since each row is an array of Standard PHP Object (which contains the column names as keys), you can then extract the Column Names from the first row and then use it to construct the Table Header. Afterwards, you can just continue building Rows containing the actual Data you want. The Code below illustrates how:
<?php
function cron_job() {
$strOutput = "<table class='cron-tbl'>";
$this->load->model('home/Home_model');
$buyer = $this->Home_model->cron_job_buyer();
$this->load->library('email', array('mailtype' => 'html'));
$seller = $this->Home_model->cron_job_seller();
$cue = 0;
foreach ($seller as $key => $row) {
if($cue == 0){
// CREATE THE HEADER ROW:
$strOutput .= "<tr class='cron-head-row'>" . PHP_EOL;
foreach($row as $rowName=>$rowVal){
$strOutput .= "<th class='cron-head-cell'>{$rowName}</th>" . PHP_EOL;
}
$strOutput .= "</tr>" . PHP_EOL;
$strOutput .= "<tbody class='cron-body'>" . PHP_EOL;
}
// CREATE THE TABLE-BODY CELL
$strOutput .= "</tr>" . PHP_EOL;
foreach ($row as $rowKey => $data) {
$strOutput .= "<td class='cron-data-cell'>{$data}</td>" . PHP_EOL;
}
$strOutput .= "</tr>" . PHP_EOL;
$cue++;
}
$strOutput .= "</tbody>" . PHP_EOL;
$strOutput .= "</table>" . PHP_EOL;;
return $strOutput;
}
echo (cron_job());
Cheers & Good Luck...
Test it out yourself HERE.
You are doing correct but need some modifications
What you need to do is in you second foreach() loop you need to convert your object to array and take out the array keys array_keys($array) in a variable and print this keys to variable. As shown bellow.
$table = "<table border='1'>";
foreach($seller as $key=>$row) { //you don't need to loop twice
$table .="<tr>";
// creating a table heading
if($key === 0 ){
$cols = array_keys((array)$row); // Convert the object to array and take out all keys of array and assign to $cols variable
$table .="<th>".implode("</th><th>", $cols);
$table .="</th></tr><tr>";
}
// table heading end
$table .= '<td>'. implode('</td><td>', (array)$row). '</td>';
$table .= "</tr>";
}
$table .="</table>";
echo $table;
Try this way.
I guess html tag, body tag are missing. That's why didnot display table the way you want.
My suggestion is that for html part, it is better if put in view.
I have create view page cron_job_seller.php with bootstrap.
// Model - Change to this
public function cron_job_seller()
{
$this->db->select('*');
$this->db->from('wc_seller_products');
return $this->db->get();
}
// Controller
public function cron_job() {
$this->load->model('home/Home_model');
$this->load->library('email', array('mailtype'=>'html'));
$buyer = $this->Home_model->cron_job_buyer();
$seller = $this->Home_model->cron_job_seller();
$data['seller'] = $seller // Send data to View
// Create cron_job_seller.php file in Views Folder.
$this->load->view('cron_job_seller', $data);
}
// View cron_job_seller.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sample Table</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table table-bordered">
<?php foreach($seller->result() as $row) { ?>
<tr>
<td><?php echo $row->colname_1; ?></td>
<td><?php echo $row->colname_2; ?></td>
<td><?php echo $row->colname_3; ?></td>
<td><?php echo $row->colname_4; ?></td>
</tr>
<?php } ?>
</table>
</div>
</body>
</html>

Mysql fetch assoc with PHP MYSQL in a table format

I have a code like this.
Code:
<?php
$book_query = mysql_query("select * from book_master')");
while($book_query_fetch = mysql_fetch_assoc($book_query)){
echo "<pre>";
print_r($book_query_fetch);
echo "</pre>"
}
?>
Output:
Array
(
[Book_Name] => Book1
[Book_ID] => 123
)
Array
(
[Book_Name] => Book2
[Book_ID] => 124
)
Expected Output: (in a table)
Book Name Book_ID
Book1 123
Book2 124
How can I achieve this?
EDIT:
The header part is a dynamic load. so i need the table header also in a loop
I don't know where you stuck doing that, but you can do below,
echo "<table>";
$i = 0;
while($row = mysql_fetch_assoc($book_query))
{
if($i == 0){
$columns = array_keys($row);
echo "<th>";
foreach($columns as $column){
echo "<td> $column</td>";
}
echo "</th>";
}
echo'<tr>';
echo '<td>'.$row['Book_Name'].'</td>';
echo '<td>'.$row['Book_ID'].'</td>';
echo '</tr>';
$i++;
}
echo "</table>";
Waring: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Try this-
<?php
$book_query = mysql_query("select * from book_master')");
echo "<table>";
echo"<tr><td>Book Name</td><td>Book_ID</td></tr>";
while($book_query_fetch = mysql_fetch_assoc($book_query)){
echo"<tr><td>".$book_query_fetch['Book_Name']."</td><td>".$book_query_fetch['Book_ID']."</td></tr>";
}
echo "</table>";
?>
Along with Rikesh's code, Use the array_keys() function. this will fetch all the keys of the subset array.
So you can fetch the keys also dynamically.
Hope this helps you.
you can do this
<table>
<?php
$book_query = mysql_query("select * from book_master')");
$book_query_fetch = mysql_fetch_assoc($book_query); ?>
<th>
<td><?php echo $book_query_fetch['book_name']; ?></td>
<td><?php echo $book_query_fetch['Book_ID']; ?> </td>
</th>
<?php while($book_query_fetch){ ?>
<tr>
<td><?php echo $book_query_fetch['Book_Name']; ?></td>
<td><?php echo $book_query_fetch['Book_ID']; ?></td>
</tr>
<?php } ?>
</table>
Try this
while($row = mysql_fetch_assoc($book_query))
{
echo'<tr><th>'.
$columns = array_keys($row);
foreach($columns as $column){
echo "<td> $column</td>";
}
.'</th></tr><tr>';
echo '<td>'.$row['Book_Name'].'</td>';
echo '<td>'.$row['Book_ID'].'</td>';
echo '</tr>';
}
echo "</table>";
//try this
<?php
$book_query = mysql_query("select * from book_master')");
while($book_query_fetch = mysql_fetch_assoc($book_query)){
echo "<pre>";
$a="<table><tr>";
foreach ($book_query_fetch as $key=>$value){
$a="<th>".$key."</th>"
}
exit;
}
$a="</tr>"
while($book_query_fetch = mysql_fetch_assoc($book_query)){
$a="<tr>";
foreach ($book_query_fetch as $key=>$value){
$a="<td>".$value."</td>"
}
$a="</tr>";
}
$a="</table>"
echo $a;
?>

How to display a php 3 level array in table form

Currently I have a PHP 3 level array. How do I display it in a table form? Using print_r I could display out the full array but I need to beautify it to show in a table form. Is it possible?
Sample of the array to be inserted is as shown in another posting: PHP foreach with Nested Array?
So... each level of the array should be an embedded table?
<table>
<?php // FIRST LEVEL
foreach ($myArray as $first_level): ?>
<tr>
<td>The header of the first level, here's some data <?php echo $first_level['some_data']; ?></td>
</tr>
<tr>
<td>
<table>
<?php // SECOND LEVEL
foreach($first_level['second_level'] as $second_level): ?>
<tr>
<td><?php echo $second_level['some_data']; ?></td>
</tr>
<?php endforeach; ?>
</table>
</td>
</tr>
<?php endforeach; ?>
</table>
..and keep repeating the pattern
So many ways to do it, even more so since you didn't provide a template for the output format ....
Let's assume each element $e of the input array $src stands for one row in the table.
Then $e[0] is the string element (one, two, three) and $e[1] is the corresponding array 1,2,3, 4,5,6 or 7,8,9.
Let's put $e[0] into <th>...</th> elements.
foreach( $src as $e ) {
echo '<th>', $e[0], '</th>';
}
and then wrap each element in $e[1] in <td>....</td>.
foreach( $src as $e ) {
echo '<th>', $e[0], '</th>';
foreach($e[1] as $v) {
echo '<td>', $v, '</td>';
}
}
now wrap that into another <tr>...</tr> and you are done
foreach( $src as $e ) {
echo '<tr>';
echo '<th>', $e[0], '</th>';
foreach($e[1] as $v) {
echo '<td>', $v, '</td>';
}
echo "</tr>\r\n";
}
the same thing a bit shorter (see http://docs.php.net/join)
<?php
$src = getData();
foreach( $src as $e ) {
echo '<tr><th>', $e[0], '</th><td>', join('</td><td>', $e[1]), "</td></tr>\n";
}
function getData() {
return array(
array( 'one', array(1,2,3) ),
array( 'two', array(4,5,6) ),
array( 'three', array(7,8,9) )
);
}
the output is
<tr><th>one</th><td>1</td><td>2</td><td>3</td></tr>
<tr><th>two</th><td>4</td><td>5</td><td>6</td></tr>
<tr><th>three</th><td>7</td><td>8</td><td>9</td></tr>
see also: http://docs.php.net/htmlspecialchars

Categories