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.
Related
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!
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);
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;
}
I am able to display all the array elements using the code below but I would like to know how can I display several array elements only (for example 4th, 6th and 11th). Could you please help me.
$rates = $data->Rates->ExchangeRate;
if (is_array($rates) && count($rates) > 0) {
echo '<table><tr><th>ISO</th><th>Rate</th></tr>';
foreach ($rates as $rate) {
echo '<tr>';
echo '<td>' . $rate->ISO . '</td><td>' . $rate->Rate . '</td></tr>';
echo '</tr>';
}
echo '</table>';
}
Just make an array of allowable key values and everytime check if the current key is included:
$rates = $data->Rates->ExchangeRate;
$allow = array(4,6,11);
if (is_array($rates) && count($rates) > 0) {
echo '<table><tr><th>ISO</th><th>Rate</th></tr>';
foreach ($rates as $key => $rate) {
if(!in_array($key, $allow){
continue;//if not allowed, go to next iteration
}
echo '<tr>';
echo '<td>' . $rate->ISO . '</td><td>' . $rate->Rate . '</td></tr>';
echo '</tr>';
}
echo '</table>';
}
You could filter the array in any number of ways before iterating over it, or you could use a condition inside the loop
$rates = $data->Rates->ExchangeRate;
if (is_array($rates) && count($rates) > 0) {
echo '<table><tr><th>ISO</th><th>Rate</th></tr>';
$count = 0;
$show = array(4, 8, 11);
foreach ($rates as $rate) {
if ( in_array($count++, $show) ) {
echo '<tr>';
echo '<td>' . $rate->ISO . '</td><td>' . $rate->Rate . '</td>';
echo '</tr>';
}
}
echo '</table>';
}
Other answers have given solutions but i think are slower than one posted here (use an array of included indices i.e $included_indices = array(4,6,11);):
$rates = $data->Rates->ExchangeRate;
if (is_array($rates) && count($rates) > 0) {
echo '<table><tr><th>ISO</th><th>Rate</th></tr>';
foreach ($included_indices as $included_indice) {
$rate = $rates[$included_indice];
echo '<tr>';
echo '<td>' . $rate->ISO . '</td><td>' . $rate->Rate . '</td></tr>';
echo '</tr>';
}
echo '</table>';
}
I'm trying to connect four tables. order_history, orders_list, infistall_order, and delivery_orders. When I run the code into the table of order_history, the results are as what I am expecting. But when I run the code into the webpages, it only selects the value from the table of order_history.
Note: What I mean with running the code into the table of order_history is when I enter phpMyAdmin and go to the order_history table and run SQL there with the SQL code I have.
<?php
include ("config.php");
$results = $mysqli->query
("
SELECT orders_history.transaction_id,
orders_history.items,
orders_history.quantity,
orders_history.one_product_price,
orders_list.status,
orders_list.invoices,
orders_list.payment_method,
orders_list.order_method,
infistall_order.address,
delivery_orders.address,
delivery_orders.service,
delivery_orders.cost,
delivery_orders.city
FROM orders_history
LEFT JOIN orders_list
ON orders_history.transaction_id = orders_list.transaction_id
LEFT JOIN infistall_order
ON orders_history.transaction_id = infistall_order.transaction_id
LEFT JOIN delivery_orders
ON orders_history.transaction_id = delivery_orders.transaction_id
WHERE orders_list.customer_name = 'Klaudia'"
);
Actually I am trying to collect information from all column in all table based on the transaction_id.
$orders = array();
$html = '';
if ($results) {
while($obj = $results->fetch_object()) {
$orders[$obj->transaction_id][$obj->items] = array('quantity' => $obj->quantity, 'invoices' => $obj->one_product_price);
}
$html .= '<table width="70%"><tr>';
$html .= '<td>items</td>';
$html .= '<td>quantity</td>';
$html .= '<td>one_product_price</td>';
$html .= '<td>status</td>';
$html .= '<td>invoices</td>';
$html .= '<td>payment_method</td>';
$html .= '<td>order_method</td>';
$html .= '<td>address</td>';
$html .= '<td>service</td>';
$html .= '<td>cost</td>';
$html .= '<td>city</td></tr>';
foreach ($orders AS $order_id => $order) {
$html .= '<tbody><tr><td rowspan="' . count($order) . '">' . $order_id . '</td>';
$row = 1;
foreach ($order AS $item => $data) {
if ($row > 1) { $html .= '</tr><tr>'; }
$html .= '<td>' . $item . '</td>';
$html .= '<td>' . $data['items'] . '</td>';
$html .= '<td>' . $data['quantity'] . '</td>';
$html .= '<td>' . $data['one_product_price'] . '</td>';
$html .= '<td>' . $data['status'] . '</td>';
$html .= '<td>' . $data['invoices'] . '</td>';
$html .= '<td>' . $data['payment_method'] . '</td>';
$html .= '<td>' . $data['order_method'] . '</td>';
$html .= '<td>' . $data['address'] . '</td>';
$html .= '<td>' . $data['service'] . '</td>';
$html .= '<td>' . $data['cost'] . '</td>';
$html .= '<td>' . $data['city'] . '</td>';
$row++;
}
$html .= '</tr><tbody>';
}
$html .= '</table>';
}
echo $html;
?>
On your loop:
while($obj = $results->fetch_object()) {
$orders[$obj->transaction_id][$obj->items] = array(
'quantity' => $obj->quantity,
'invoices' => $obj->one_product_price
);
}
You can change it to:
while($obj = $results->fetch_object()) {
$orders[$obj->transaction_id][$obj->items][] = array(
'quantity' => $obj->quantity,
'invoices' => $obj->one_product_price
);
}
It will prevent the data from replacing one to another, the [] sign on array is make the array to become dynamic, the key will be count from 0 and will be increment by 1 as you add more data into that array.