I am using the below code to make a HTML table. I searched online for PHP get column headings but couldn't find any information (only information on rows). Is it possible to use a while loop and print the column headings from the SQL instead of having them hardcoded as below?
Code
$stid = oci_parse($conn, "
SELECT *
FROM
(
SELECT orders.order_no, orders.porder_no, orders.date, order_totals.value
FROM orders, order_totals
WHERE orders.order_no = order_totals.order_no
AND orders.account_no = '" . $_SESSION['session_account'] . "'
ORDER BY orders.order_no DESC
)
WHERE ROWNUM <= 15
");
oci_execute($stid);
echo "<table class='table'>
<thread>
<tr>
<th>Order No</th>
<th>Purchase Order No</th>
<th>Date</th>
<th>Value</th>
</tr>
</thread>
<tbody>";
while ($row = oci_fetch_array($stid, OCI_NUM)) {
echo "<tr>";
echo '<td>' . $row[0] . '</td>';
for ( $ii = 1; $ii < count($row); $ii++ ) {
echo "<td>" . $row[$ii] . "</td>";
}
echo "</tr>";
}
echo "</tbody> </table>";
Use this code this may help you, use oci_field_name() to get the column name
echo "<table class='table'>
<thread>
<tr>";
$ncols = oci_num_fields($stid);// to get column number
for ($i = 1; $i <= $ncols; $i++) {// index start from 1
$column_name = oci_field_name($stid, $i);
echo "<th>".$column_name."</th>";
}
echo "</tr>
</thread>
<tbody>";
You are looking for column name property that is already made available by PHP MySQL or MySQLI or PDO APIs.
Here is an example - http://www.php.net/manual/en/function.mysql-field-name.php
Good luck.
Related
Currently, in our office website, there is a userinput textbox and after inserting, results from database will be shown below. There are 4 results Lot ID, Product, EWSFLOW and Zone.Among them, only zone is different. I want to do that Lot ID, Product and EWSFlow must show at once and if that entered values have 5 different zones, Zone must shown Zone: 1,2,3,4,5. << First problem has been solved. And right now, I tried to add check boxes for each zone and checkbox must shown beside each zone. But currently, checkboxes are showing at the top. Also, count of the checkboxes must be same as Zones. lets say if the inserted value have 5 zones, it has to show 5 checkboxes besides of it (Example: Zone : [checkbox] 1).
Checkboxes are showing at top
echo "<table id='corwafer'>";
$arr = array();
while ($row = mysqli_fetch_assoc($result1)) {
$field1name = $row["lotid"];
$field2name = $row["product"];
$field3name = $row["ewsflow"];
$field4name = $row["zone"];
$key = $field1name + ":" + $field2name + ":" + $field3name;
if (!in_array($key, $arr)){
echo "<tr>";
echo "<th >Lot ID:</th>";
echo "<td >$field1name</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Product:</th>";
echo "<td>$field2name</td>";
echo "</tr>";
echo "<tr>";
echo "<th>EWSFLOW: </th>";
echo "<td>$field3name</td>";
echo "</tr>";
array_push($arr, $key);
}
echo "<tr>";
echo "<th>Zone:</th>";
echo "<input type='checkbox' name='chkzone' value='chkzone'>";
echo "<td>$field4name</td>";
echo "</tr>";
}
echo "</table>";
You can define an array and put lotid, product and ewsflow into it as merged inside the loop. Then before echoing check if it's already used before :
$arr = array();
while ($row = mysqli_fetch_assoc($result1)) {
$field1name = $row["lotid"];
$field2name = $row["product"];
$field3name = $row["ewsflow"];
$field4name = $row["zone"];
$key = $field1name + ":" + $field2name + ":" + $field3name;
if (!in_array($key, $arr)){
echo "<tr>";
echo "<th >Lot ID:</th>";
echo "<td >$field1name</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Product:</th>";
echo "<td>$field2name</td>";
echo "</tr>";
echo "<tr>";
echo "<th>EWSFLOW: </th>";
echo "<td>$field3name</td>";
echo "</tr>";
array_push($arr, $key);
}
echo "<tr>";
echo "<th>Zone:</th>";
echo "<td>$field4name</td>";
echo "</tr>";
}
You can change your query and use GROUP BY feature of MySQL. Below is the query. Ignore any spelling mistakes.
$sql = "SELECT lotid, product, ewsflow, GROUP_CONCAT(zone) FROM productdb.tbl_correlationwafer WHERE lotid = ? GROUP BY lotid, product, ewsflow ORDER BY lotid";
$pq = $mysqli->prepare($sql);
$pq->bind_param('i', $productlotid);
$pq->execute();
$result = $pq->get_result();
$data = $result->fetch_all();
GROUP_CONCAT() function returns a string with concatenated non-NULL value from a group.
GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country".
You can accomplish the desired output in a much simpler fashion if you were to use group_concat in the SQL query to gather together the various zone columns into a formatted value - then the PHP really needs only process a single row in the recordset and display the desired table format.
The SQL takes advantage of a prepared statement to help mitigate SQL injection - matters not that it is an internal website IMO - always better to be secure!
$sql='SELECT
`lotid`,
`product`,
`ewsflow`,
group_concat( distinct `zone` order by `zone` asc separator ", " ) as `zone`
FROM `productdb`.`tbl_correlationwafer`
WHERE `lotid` = ?
ORDER BY `lotid`';
$stmt=$conn->prepare( $sql );
$stmt->bind_param('s', $productlotid );
$stmt->execute();
$stmt->bind_result( $lotid, $product, $ewsflow, $zone );
$stmt->fetch();
printf('
<table id="corwafer">
<tr>
<th>Lot ID:</th>
<td>%1$s</td>
</tr>
<tr>
<th>Product:</th>
<td>%2$s</td>
</tr>
<tr>
<th>EWSFLOW:</th>
<td>%3$s</td>
</tr>
<tr>
<th>Zone:</th>
<td>%4$s</td>
</tr>
</table>',
$lotid,
$product,
$ewsflow,
$zone
);
I have successfully done the php script that connect to my database and return desired data. But i need to extend this script to insert a variable that will show the price with some calculations (tax,no-tax,margin etc.).
This script show me only price value of the first database row 0.00 in all fetched rows and its not correct - for the first database row is ok because product have 0.0000 price, but the other rows are filled with correct values. It seems like the while loop dont like my $styledprice variable . I can't figure how to show correct field values in all lines. Any ideas much apppreciated? I'm a PHP beginner!
$pricequery = "SELECT rrp FROM my_products";
$b2bprice = mysql_query($pricequery);
$rrps = mysql_fetch_array($b2bprice);
$price = $rrps['rrp'];
$styledprice = number_format($price, 2, '.', '');
$query = mysql_query("
SELECT
CONCAT(' <td> ',p.id,' </td><td> ',p.manufacturer,' </td><td> ',p.reference,' </td><td> ',p.name,' </td><td> ',p.quantity,' <td> ','".$styledprice."',' </td> ') AS row
FROM my_products p
");
echo "
<table>
<tr>
<td><h5>ID</h5></td>
<td><h5>Manufacturer</h5></td>
<td><h5>PN</h5></td>
<td><h5>Name</h5></td>
<td><h5>Quantity</h5></td>
<td><h5>Price</h5></td>
</tr>";
while($row=mysql_fetch_array($query))
{
echo "<tr>".$row['row']."</tr>";
}
echo "
</table>";
Yes i know about mysql_ functions that are deprecated.
Something like this should work better.
It seperates the resultset from the database and the output via HTML.
// Get the Result Set
$result = mysql_query("SELECT p.id, p.manufacturer, p.reference, p.name, p.quantity FROM my_products p");
// Convert the rows and columns from the Result Set to a PHP Array
$data = array(); // empty array
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
// Now you have access any row or column
echo "<table>";
foreach($data as $row){
// prepare the data
$formatttedQuantity = number_format($row['quantity'], 2, '.', '');
// show each Table Row
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['manufacturer'] . "</td>";
echo "<td>" . $row['reference'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $formatttedQuantity . "</td>";
echo "</tr>";
}
echo "</table>";
It looks like you can do this all in one sql command like:
<?php
$sql = "SELECT * FROM my_products";
$result = mysql_query( $sql );
echo "
<table>
<tr>
<td><h5>ID</h5></td>
<td><h5>Manufacturer</h5></td>
<td><h5>PN</h5></td>
<td><h5>Name</h5></td>
<td><h5>Quantity</h5></td>
<td><h5>Price</h5></td>
</tr>";
while( $row=mysql_fetch_array( $result ) ){
$price=$row['rrp'];
$styledprice = number_format( $price, 2, '.', '' );
echo "
<tr>
<td>{$row['id']}</td>
<td>{$row['manufacturer']}</td>
<td>{$row['reference']}</td>
<td>{$row['name']}</td>
<td>{$row['quantity']}</td>
<td>{$styledprice}</td>
</tr>";
}
echo "
</table>";
?>
I have a site where members can mark other members as 'a favourite'. User are able to search the members table in various ways and I want to show from any of the results that are returned whether or not the users returned are favourites of the current user.
This is some very simplified code I have been using to try and get this query to work but I just can't figure it out. Whenever I add 'GROUP BY' to avoid duplicate results from my LEFT JOIN the 'if' statement does not work. The 'if' statment does work however, if I omit the 'GROUP BY' but I get all rows from members table and the favourites table. Thanks.
$result = mysqli_query($db_conx, "SELECT members.*, user_favourites.* FROM members LEFT JOIN user_favourites ON members.id = user_favourites.fav_id GROUP BY members.id");
echo "<table border=''>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>A favourite of User</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
if ($visitor == $userid ){
$msgs = "x";
}
else { $msgs = "0";
}
echo "<td>". $msgs. "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I suggest to you, tu use 2 query's insted one. Simple query is a fast querys. If your site scale up, your query will be slow query and it cause performance problems.
Idea:
For one hand: SELECT FROM members, get all and put it inside array, key=member.id
$members[$row['member_id']]=$row;
On the other hand: SELECT * FROM user_favourites, and put it inside the previous array, refereced by the key fav_id use distinc if you have duplicates.
$members[$row['fav_id']]['favourites']=$row;
Perfect now you have all you need, an array with all information, iterate it.
JilianJ something like this:
<?
//Prepare
$all_users=array()
$query_users='SELECT * from user';
$query_favourites='SELECT * FROM user_favourites';
//Now I find all members information
$users=mysqli_query($db_conx,$query_users);
while($user = mysqli_fetch_array($users)) {
$all_users[$user['id']]=$user;
}
//Now I add favourite information to the users information
$favourites=mysqli_query($db_conx,$query_favourites);
while($favourite = mysqli_fetch_array($favourites)) {
$all_users[$favourite['fav_id']]['fovourite'][]=$favourite['fav_id'];
}
?>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>A favourite of User</th>
</tr>
<? foreach ($information as $key=>$item) {?>
<tr>
<td><?=$item['firstname'];?></td>
<td><?=$row['lname'];?></td>
<td><?=$row['email'];?></td>
<td>
<? foreach($item['favourites'] as $key2=>$item2) { ?>
<p><?=$all_members[$item2]['name];?></p>
<? } ?>
</td>
</tr>
<? } ?>
</table>
Good luck
Background
I am using the below code to generate a HTML table based on SQL results.
Code
$stid = oci_parse($conn, "
SELECT *
FROM
(
SELECT orders.order_no, orders.porder_no, orders.date, order_totals.value
FROM orders, order_totals
WHERE orders.order_no = order_totals.order_no
AND orders.account_no = '" . $_SESSION['session_account'] . "'
ORDER BY orders.order_no DESC
)
WHERE ROWNUM <= 15
");
oci_execute($stid);
echo "<table class='table'>
<thread>
<tr>
<th>Order No</th>
<th>Purchase Order No</th>
<th>Date</th>
<th>Value</th>
</tr>
</thread>
<tbody>";
while ($row = oci_fetch_array($stid, OCI_NUM)) {
echo "<tr>";
echo '<td>' . $row['0'] . '</td>';
echo "<td>" . $row['1'] . "</td>";
echo "<td>" . $row['2'] . "</td>";
echo "<td>" . $row['3'] . "</td>";
echo "</tr>";
unset($row);
}
echo "</tbody>
</table>";
Question
Is it possible to make the HTML table generation part in the code more dynamic, so that if I need to add an additional column for example I can just ammend the SQL part in the code?
I had an idea to set the column headings using AS in SQL and I can amend the SQL to use AS to show the real column headings I want for example
SELECT orders.order_no AS "Order No"
, orders.porder_no AS "Purchase Order No"
, orders.date AS "Date"
, order_totals.value AS "Total"
but what about the HTML table part, is there some method to just print all columns and rows dynamically, like maybe create a function printTable that would handle any table?
The $row var is an array so you can loop over that too. Since you want to treat your first field differently write it out before the loop and start the loop at 1.
while ($row = oci_fetch_array($stid, OCI_NUM)) {
echo "<tr>";
echo '<td>' . $row[0] . '</td>';
for ( $ii = 1; $ii < count($row); $ii++ ) {
echo "<td>" . $row[$ii] . "</td>";
}
echo "</tr>";
}
I don't know what the unset($row) was for, so I left it out.
You can use:
SELECT * FROM {TABLENAME}
Then fetch an array.
You can get data with $row['{FIELDNAME}']
You can use double loop:
$results = $PDO->fetchAll(PDO::FETCH_ASSOC); // here is all columns and rows from db query.
echo '<table><tr>';
// loop only first row to get header
foreach ($results[0] as $header => $value) {
echo "<th>{$header}</th>"
}
echo '</tr>';
// loop all rows
foreach ($results as $row) {
echo '<tr>';
// and loop any number of columns
foreach ($row as $cellName => $cell) {
// If you have only one special case, than use if statement
switch ($cellName) {
case 'order_no':
echo "<td><a href='http://example.com/getOrder?id={$cell}'>{$cell}</a></td>";
break;
default: echo "<td>{$cell}</td>";
}
}
echo '</tr>';
}
echo '</table>';
I have a drop down menu, which is filled from a database. When I select a value in the menu it displays a table of the data selected from the database. I'd like to change this to an HTML5 range slider. So far with no luck. I also want to show the values (dates) beside the range as I move along it.
This is the code to the drop down menu:
// Set SQL string
$query = "SELECT * FROM Test";
// Execute SQL
$result = mysql_query($query);
// Find number of rows in the resulting recordset array
$num = mysql_numrows($result);
// Initialise loop counter
$i = 0;
echo ("<form><select name='users' onchange='showUser(this.value)'>");
// Loop through recordset until end
while ($i < $num) {
// Associate variables for result at position i at table location specified
$Time = mysql_result($result, $i, "Time");
// Echo each entry as an OPTION for the Select List
echo ("<option value=\"$Time\">$Time</option>");
// Increment Loop Counter
$i++;
}
echo ("</select></form><br>");
gettime.php:
$sql = "SELECT * FROM Test WHERE Time = '" . $q . "'";
$resultb = mysql_query($sql);
if (!$resultb) {
echo "<p>The following SQL failed</p><p>" . $sql . "</p>";
}
echo "<table border='1'>
<tr>
<th>Time</th><th>First PC Room</th>
<th>First Group Study Room 1</th>
<th>First Group Study Room 2</th>
<th>First Main Room</th>
</tr>";
while ($rowb = mysql_fetch_array($resultb)) {
$bmsTime = $rowb['Time'];
//Convert Excel Timestamp of DB to Unix Timestamp
$unixtime=($bmsTime-25569)*86400;
$readable=date('l jS \of F Y h:i:s A',($unixtime));
echo "<tr>";
echo "<td>" . $readable . "</td>";
echo "<td>" . $rowb['firstPCroom'] . "</td>";
echo "<td>" . $rowb['firstGrpStdyRm1'] . "</td>";
echo "<td>" . $rowb['firstGrpStdyRm2'] . "</td>";
echo "<td>" . $rowb['firstmainroom'] . "</td>";
echo "</tr>";
}
echo "</table>";
Below is what I have so far on the "slider":
echo "<input id='slider' type='range' min='0' max=\"$num\" step='any' />
<span id='range'> </span>";
?>
<script>
var selectmenu=document.getElementById("slider");
var colorchange;
selectmenu.onchange=function changecolour(){
if (selectmenu.value<"0.5")
{colorchange=0}
else if (selectmenu.value>="0.5") {colorchange=Math.round(selectmenu.value)}
document.getElementById("range").innerHTML=colorchange;
}
</script>
Any help would be greatly appreciated! Thanks
Here is a jsFiddle that updates a table row using jQuery. Presumably you would replace the data with an AJAX call.
If you were a little more specific about where exactly you were having trouble, someone else may be able to tailor a solution that better fits your needs.