PHP Fetch array in table with individual styling - php

I have an array that i pull from a database that looks like this
id - name - shortlink - downloadurl - count - date
Now I want to display that array as a table so the administartor of the site can se the content of the database. For that, I'm using this code:
function build_table($array){
// start table
$html = '<table id="usertable">';
// header row
$html .= '<tr class="header">';
foreach($array[0] as $key=>$value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
And it works great.
The problem is that i wan't do display some of the columns with a different code. E.g. 'downloadurl' which is an webadress, i want to make clickable. I just can't figure out how to split up the function so that i can write the code for the individual columns.

You could try something similar to the following:
using conditionals
This is probably the most straight forward way to go about handling different attributes per column - not without its drawbacks (noted below)
// data rows
foreach( $array as $key => $value) {
$html .= '<tr>';
foreach($value as $key2 => $value2) {
if ($key2 == 'downloadurl') {
$html .= '<td>Download</td>';
} else {
$html .= '<td>' . $value2 . '</td>';
}
}
$html .= '</tr>';
}
using switch statement
If you decide on this route, it may be a bit easier to manage in the long run as if () elseif () else() can become difficult to read over time.
foreach($value as $key2 => $value2) {
switch($key2) {
case 'downloadurl':
$html .= '<td>Download</td>';
break;
default:
$html .= '<td>' . $value2 . '</td>';
}
}

use this function to generate urls:
function getURL($downloadURL)
{
$html = "<a href = '$downloadURL'>Download</a>";
return $html;
}
And your function build_table():
function build_table($array){
// start table
$html = '<table id = "usertable">';
// header row
$html .= '<tr class = "header">';
foreach($array[0] as $key => $value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key => $value){
$html .= '<tr>';
foreach($value as $key2 => $value2){
$value2 = ($key2 == 'downloadurl') ? getURL($value2) : $value2;
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}

Related

First row of mysql data fetched through PHP is not displayed in the table

I have written a function to display the data fetched from MySQL database using PHP mysqli_query( $db_conn, $sql ); when I am calling the following display function first row of the data is not displayed. Please suggest how can I get the first row.
function display_data($retval) {
$output = '<table border="1">';
foreach($retval as $key => $var) {
$output .= '<tr>';
foreach($var as $k => $v) {
if ($key === 0) {
$output .= '<td><strong>' . $k . '</strong></td>';
} else {
$output .= '<td>' . $v . '</td>';
}
}
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
Code for display data
if (isset( $_POST['submit'])){
$_date = $_POST["date"];
//echo $_date;
$resultArray = array();
$sql = "SELECT * FROM outstanding WHERE ondate='$_date' ";
};
/*echo json_encode($retval);*/
$retval = mysqli_query( $db_conn, $sql );
display_data($retval);
}
EDIT 2:
I was able to achieve this by the following code, please suggest if there are any better methods to display in HTML/web page.
//code to display data in table form
function display_data($retval)
{
$output = '<table border="1">';
foreach ($retval as $key => $var)
{
echo $key;
if ($key === 0)
{
$output .= '<tr>';
foreach ($var as $k => $v)
{
$output .= '<th><strong>' . $k . '</strong></th>';
};
$output .= '</tr>';
};
$output .= '<tr>';
foreach ($var as $k => $v)
{
if ($key === 0)
{
$output .= '<td>' . $v . '</td>';
echo $v;
}
else
{
$output .= '<td>' . $v . '</td>';
};
};
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
The reason why you cannot see the first row is that you never display it. If the iteration is on the first row, you only display the header, but you skip the data.
foreach ($var as $k => $v) {
if ($key === 0) {
// If this is the first row, you display the key, but not the value.
$output .= '<td><strong>' . $k . '</strong></td>';
} else {
$output .= '<td>' . $v . '</td>';
}
}
Your suggested solution is the correct one. You need to loop the first row twice. Once to display the header and then once to display the data.
function display_data1($retval) {
$output = '<table border="1">';
foreach ($retval as $key => $var) {
if ($key === 0) {
// If key is 0, meaning first row...
$output .= '<thead><tr>';
// create new HTML row and loop the first MySQL row
foreach ($var as $k => $v) {
$output .= '<th>' . $k . '</th>';
}
$output .= '</tr></thead>';
}
// Then loop as normal all rows including the first one.
$output .= '<tr>';
foreach ($var as $k => $v) {
$output .= '<td>' . $v . '</td>';
}
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough!

PHP array to table with more than two columns

I have a little code that combines two arrays into a table with 2 columns. This works. But now I have a new array with values from $file3. I understand how to make a table with two columns, but how can I add a third column with the content of $file3?
<?php
$file1 = "c:/presencetool/ramfile1.txt";
$file2 = "c:/presencetool/ramfile2.txt";
$file3 = "c:/presencetool/ramfile3.txt"; //new file
if(file_exists($file1) && file_exists($file2))
{
$line1 = file($file1, FILE_IGNORE_NEW_LINES);
$line2 = file($file2, FILE_IGNORE_NEW_LINES);
$line3 = file($file3, FILE_IGNORE_NEW_LINES); //new array
$combine = array_combine($line1, $line2); //I want to also combine $line3 here
$html = '<table align="center">';
$html .= '<tr><td width="350px";></td><td></td></tr>';
$i = 1;
foreach ($combine as $key => $value):
$html .= '<tr class="'.$value.'">';
$html .= '<td font-size:"90pt">'.$key.'</td>';
$html .= '<td font-size:"90pt">'.$value.'</td>';
//here something like $html .= '<td font-size:"90pt">'.$value2.'</td>';
$html .= '</tr>';
$i++;
endforeach;
$html .= '</table>';
echo $html;
}
In $file1, $file2 and $file3 are names, addresses and emails of some users.(one value per line)
if your array looks like this :
$line[] = ['name' => 'name1','email' => 'email#mail.com'];
$line[] = ['name' => 'name2','email' => 'email2#mail.com'];
$line[] = ['name' => 'name3','email' => 'email3#mail.com'];
Then try the below, hope will help you
$html = '<table align="center" border="1" width="50%">';
$html .= '<tr><th>Name</th><th>Email</th><th>Address</th></tr>';
for($i=0;$i<count($line1);$i++){
$html .= '<tr class="'.$line1[$i].'">';
$html .= '<td font-size:"90pt">'.$line1[$i].'</td>';
$html .= '<td font-size:"90pt">'.$line2[$i].'</td>';
$html .= '<td font-size:"90pt">'.$line3[$i].'</td>';
$html .= '</tr>';
}
$html .= '</table>';
echo $html;

Print HTML table in foreach loop

I am trying to fetch data in table row. The problem is I am getting different output. All columns are printed in one column.
foreach ($user1 as $key => $value) {
$date1 = date('Y-m-d', strtotime($date));
$timing= date('H:i:s', strtotime($date));
$error_p = implode(' ', $product[0])."<br>";
$error_d = implode(' ', $checked[0])."<br>";
$html = '<table border="1">';
$html .= "<tr>";
$html .= "<td bgcolor='#D0D0FF'>$error_p</td>";
$html .= "<td bgcolor='#D0D0FF'>$error_d</td>";
$html .= "</tr>";
$html .= "</table>";
$pdf->WriteHTML($html);
}
Output is like this:
The problem is that you create a new table element for every user. so put the table outside of your foreach loop so that it looks something like this:
$html='<table border="1">';
foreach ($user1 as $key =>$value) {
$date1 = date('Y-m-d',strtotime($date));
$timing= date('H:i:s',strtotime($date));
$error_p = implode(' ', $product[0]);
$error_d = implode(' ', $checked[0]);
$html .= "<tr>";
$html .= "<td bgcolor='#D0D0FF'>$error_p</td>";
$html .= "<td bgcolor='#D0D0FF'>$error_d</td>";
$html .= "</tr>";
}
$html.="</table>";
$pdf->WriteHTML($html);

Display PHP Query results in table regardless of # of columns returned?

So I'm exploring the wonderful world of PHP and I'm still creating very dirty, poorly build code but I'm trying to get better! So my question is as follows:
Is there a way to automatically calculate the columns in the result set and spit out a pretty HTML table regardless of query used?
Here the current code:
<?php
include '../includes/connect.php';
include '../includes/queries.php';
$stid = oci_parse($conn, $export);
oci_execute($stid);
echo "<table class='pure-table pure-table-striped' style='font-size:11px;'><thead><tr><th>Name</th><th>File Name</th><th>Export Date</th></tr></thead>";
while (oci_fetch($stid)) {
echo "<tr><td>" . oci_result($stid, 'DISPLAY_NAME') . "</td>";
echo "<td>" . oci_result($stid, 'LAST_EXPORT_FILE') . "</td>";
echo "<td>" . oci_result($stid, 'LAST_EXPORT_DATE') . "</td></tr>";
}
echo "</table>\n";
oci_free_statement($stid);
oci_close($conn);
I'd like to use the same table every time, but just have it auto detect column header names and number of columns and return it in a table.
Is it possible or does it make sense?
I do exactly that using PDO.
$out = '';
$q = $conn->prepare($SQL);
if ($q->execute()) {
$rows = $q->fetchAll();
if (!empty($rows)) {
//We have something
$out .= "<table class='pure-table pure-table-striped' style='font-size:11px;'>";
$first = true;
//iterate on rows
foreach($rows as $row) {
//Clean out all the numeric keys - stops duplicate values
foreach ($row as $key => $value) {
if (is_int($key)) {
unset($row[$key]);
}
}
//header
if ($first) {
//write header
$out .= '<thead><tr>';
foreach ($row as $key => $value) {
$out .= '<th>' . $key . '</th>';
}
$out .= '</tr></thead>';
$first = false;
}
//write line
$out .= '<tr>';
foreach($row as $key => $value) {
$out .= '<td>' . $value . '</td>';
}
$out .= '</tr>';
}
$out .= '</table>';
}
}
echo ($out);

How can I find last <td> in table with PHP

I wonder how can i find out last in table with PHP, aka if that is last then i want to apply different style and content to it.
This is part of my code generating table content.
$content .= '</tr>';
$totalcols = count ($columns);
if (is_array ($tabledata))
{
foreach ($tabledata as $tablevalues)
{
if ($tablevalues[0] == 'dividingline')
{
$content .= '<tr><td colspan="' . $totalcols . '" style="background-color:#efefef;"><div align="left"><b>' . $tablevalues[1] . '</b></div></td></tr>';
continue;
}
else
{
$content .= '<tr>';
foreach ($tablevalues as $tablevalue)
{
$content .= '<td>' . $tablevalue . '</td>';
}
$content .= '</tr>';
continue;
}
}
}
else
{
$content .= '<tr><td align="center" style="border-bottom: none;" colspan="' . $totalcols . '">No Records Found</td></tr>';
}
I know there is option to do something like that with jQuery later on, but I don't want to complicate it and just solve it with php at time when i generate table.
Keep a count:
$count = 1;
foreach ($tablevalues as $tablevalue)
{
$count++;
if( $count > count( $tablevalues)) {
echo "Last td tag is up next! ";
}
$content .= '<td>' . $tablevalue . '</td>';
}
you can execute any code in last loop:
for($i=0;$i<count($tablevalues);$i++)
{
$tablevalue=$tablevalues[$i];
$content .= '<td>' . $tablevalue . '</td>';
if($i==count($tablevalues)-1){
// last loop execution
}
}
here is a somehow trick
foreach ($tablevalues as $k => $tablevalue)
{
if ($k==count($tablevalues)-1)
{
// last td of current row
$content .= '<td>' . $tablevalue . '</td>';
}
else
{
$content .= '<td>' . $tablevalue . '</td>';
}
}
I just hope that your keys of your $tablevalues set match this code.
You should use a for($i = 0; i < count($tablevalues); $i++) {} loop and consider count($tablevalues)-1 to be the last key of your array.
So that $tablevalues[count($tablevalues)-1] is your last <td>.
Why dont you use jQuery?It has provisions to do something like that.

Categories