Selecting the highest ID from a database table with PHP - php

I am trying to select one row from the database with the highest ID and echo it out to the page in a table.
I can run the query manually and it works correctly but when I try to do it dynamically via PHP; it does not work. What is wrong with my code?
<?php
$sql_query = "SELECT * FROM single_user_orders ORDER BY order_id DESC LIMIT 1";
$result = mysqli_query($dbconfig, $sql_query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
echo '<div class="row" style="margin-top: 30px;">';
echo '<div class="col-md-12">';
echo '<table class="table">';
if($count > 1) {
echo '<tr>';
echo '<th>Order ID</th>';
echo '<th>Status</th> ';
echo '<th>Order Total</th>';
echo '<th>Order Description</th>';
echo '</tr>';
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
echo '<td>'. $row['order_id'] .'</td>';
echo '<td>'. $row['status'] .'</td> ';
echo '<td>'. $row['order_total'] .'</td>';
echo '<td>'. $row['order_description'] .'</td>';
echo '</tr>';
}
}
echo '</table>';
echo '</div>';
echo '</div>';
?>

You are using while loop for fetching data again where as there is no need to fetch data again as it is already been fetched using $row = mysqli_fetch_array($result, MYSQLI_ASSOC); at the beginning.
Try following
<?php
$sql_query = "SELECT * FROM single_user_orders ORDER BY order_id DESC LIMIT 1";
$result = mysqli_query($dbconfig, $sql_query);
$row = mysqli_fetch_assoc($result);
$count = mysqli_num_rows($result);
echo '<div class="row" style="margin-top: 30px;">';
echo '<div class="col-md-12">';
echo '<table class="table">';
if ($count >= 1)
{
echo '<tr>';
echo '<th>Order ID</th>';
echo '<th>Status</th> ';
echo '<th>Order Total</th>';
echo '<th>Order Description</th>';
echo '</tr>';
// Removed while loop as data is already fetched
// you just need to echo the values now
echo '<tr>';
echo '<td>' . $row['order_id'] . '</td>';
echo '<td>' . $row['status'] . '</td> ';
echo '<td>' . $row['order_total'] . '</td>';
echo '<td>' . $row['order_description'] . '</td>';
echo '</tr>';
}
echo '</table>';
echo '</div>';
echo '</div>';
?>
while loop is not required here as only one row is being retried by using LIMIT 1. if more than one row is being retrieved, in that case while loop will do the trick for you.

Take a look on
$sql_query = "SELECT * FROM single_user_orders ORDER BY order_id DESC LIMIT 1";
and
if($count > 1) {
You always will be have only 1 row. Try to change conditions

You only show the table when MORE than 1 record is selected. Your query will return maximum one result, so the table will never show.
Use if($count >= 1) instead of if($count > 1).
Please note the 'Is greater OR Equal' notation: >=

update your code with this as there are two errors
1) count >= 1
2) while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) { //add MYSQLI_ASSOC
}

Your result set contains only 1 row .
So, mysqli_num_rows($result) will return 1 in count. So you should check
if($count==1) {
...
}

<?php
$sql_query = "SELECT * FROM single_user_orders ORDER BY order_id DESC LIMIT 1";
$result = mysqli_query($dbconfig, $sql_query);
$count = mysqli_num_rows($result);
echo '<div class="row" style="margin-top: 30px;">';
echo '<div class="col-md-12">';
echo '<table class="table">';
if($count >= 1) {
echo '<tr>';
echo '<th>Order ID</th>';
echo '<th>Status</th> ';
echo '<th>Order Total</th>';
echo '<th>Order Description</th>';
echo '</tr>';
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
echo '<td>'. $row['order_id'] .'</td>';
echo '<td>'. $row['status'] .'</td> ';
echo '<td>'. $row['order_total'] .'</td>';
echo '<td>'. $row['order_description'] .'</td>';
echo '</tr>';
}
}
echo '</table>';
echo '</div>';
echo '</div>';
?>
Try this for 1 or more orders

Related

PHP: List multiple record grouped by date

I'm trying to list multiple record from MySQL Database using PHP but when grouping it returns only one record from database, below is my PHP code I'm using.
<?php
include "connection.php";
$query = "select * from lectureupload GROUP BY submittedOn";
$result=mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
echo '<table class="table">';
echo '<thead>';
echo '<td><strong>ID</strong></td>';
echo '<td><strong>Title</strong></td>';
echo '<td><strong>Semester</strong></td>';
echo '<td><strong>Teacher</strong></td>';
echo '<td><strong>Lecture Link</strong></td>';
echo '<td><strong>Submitted On</strong></td>';
echo '</thead>';
echo '<div class="section-header">';
echo '<br>';
echo '<h3>'.$row['submittedOn'].'</h3>';
echo '</div>';
echo '<tr >';
echo '<td>'.$row['id'].'</td>';
echo '<td>'.$row['title'].'</td>';
echo '<td>'.$row['semester'].'</td>';
echo '<td>'.$row['teacherName'].'</td>';
echo '<td>'.$row['lectureLink'].'</td>';
echo '<td>'.$row['submittedOn'].'</td>';
echo '</tr>';
echo '</table>';
}
mysqli_close($conn);
?>
The current Result it gives me is somewhat like that,
My Database table is this.
Solution to this problem will be highly appreciated.
Regards.
You can't use GROUP BY clause to retrieve all records from that table. GROUP BY will always return one row per GROUP BY CONDITIONAL_COLUMN. I will suggest you below modification:
<?php
include "connection.php";
//ORDER BY submittedOn will make sure the records retrieved in ordered as per submittedOn.
$query = "select * from lectureupload ORDER BY submittedOn";
$result = mysqli_query($conn, $query);
$submitted_on_keys = array();
while ($row = mysqli_fetch_array($result)) {
if (!in_array($row['submittedOn'], $submitted_on_keys)) {
if (count($submitted_on_keys) > 0) {
//It means we have already created <table> which needs to be closed.
echo '</table>';
}
$submitted_on_keys[] = $row['submittedOn'];
echo '<table class="table">';
echo '<thead>';
echo '<td><strong>ID</strong></td>';
echo '<td><strong>Title</strong></td>';
echo '<td><strong>Semester</strong></td>';
echo '<td><strong>Teacher</strong></td>';
echo '<td><strong>Lecture Link</strong></td>';
echo '<td><strong>Submitted On</strong></td>';
echo '</thead>';
echo '<div class="section-header">';
echo '<br>';
echo '<h3>' . $row['submittedOn'] . '</h3>';
echo '</div>';
}
echo '<tr >';
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['title'] . '</td>';
echo '<td>' . $row['semester'] . '</td>';
echo '<td>' . $row['teacherName'] . '</td>';
echo '<td>' . $row['lectureLink'] . '</td>';
echo '<td>' . $row['submittedOn'] . '</td>';
echo '</tr>';
}
if (count($submitted_on_keys) > 0) {
//There is last <table> which needs to be closed.
echo '</table>';
}
mysqli_close($conn);
?>
You should group it in your PHP code rather than your SQL.
Something like this:
$lectures = [];
$result = mysqli_query($conn, "select * from lectureupload");
while ($row = mysqli_fetch_array($result)) {
$lectures[$row['submittedOn']][] = $row;
}
foreach ($lectures as $submittedOn => $rows) {
echo '<table class="table">';
echo '<thead>';
echo '<td><strong>ID</strong></td>';
echo '<td><strong>Title</strong></td>';
echo '<td><strong>Semester</strong></td>';
echo '<td><strong>Teacher</strong></td>';
echo '<td><strong>Lecture Link</strong></td>';
echo '<td><strong>Submitted On</strong></td>';
echo '</thead>';
echo '<div class="section-header">';
echo '<br>';
echo '<h3>'.$submittedOn.'</h3>';
echo '</div>';
foreach ($rows as $row) {
echo '<tr >';
echo '<td>'.$row['id'].'</td>';
echo '<td>'.$row['title'].'</td>';
echo '<td>'.$row['semester'].'</td>';
echo '<td>'.$row['teacherName'].'</td>';
echo '<td>'.$row['lectureLink'].'</td>';
echo '<td>'.$row['submittedOn'].'</td>';
echo '</tr>';
}
echo '</table>';
}

ID'd link on click

I'm creating a contact based system, i have a contact list and want it to go to a full contact page when i click on a button, but the variable is being detected as a function?
<div id="po2" style="Margin:10% ">
<h1>Contacts</h1>
<?php
$sql = "SELECT * FROM `contacts`";
$query = mysqli_query($conn, $sql);
echo '<table class="data-table">';
echo'<thead>';
echo'<tr>';
echo '<th>Forename</th>';
echo '<th>Surname</th>';
echo '<th>Other</th>';
echo'</tr>';
echo '</thead>';
echo '<tbody>';
while ($row = mysqli_fetch_array($query))
{
echo '<tr>';
echo '<td>'.$row['Forename'].'</td>';
echo '<td>'.$row['Surname'].'</td>';
echo $var==$row['Forename']("<td><a href='View.php?ID= " . urlencode($var) ."'>
<button type='button'>link</button>
</a></td>");
echo '</tr>';
}
echo'</tbody>';
echo '</table>';
?>
</div>
You are using a comparison of $var and the $row. Try setting $var to the $row each loop iteration.
echo '<thead>';
echo '<tr>';
echo '<th>Forename</th>';
echo '<th>Surname</th>';
echo '<th>Other</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while ($row = mysqli_fetch_array($query))
{
$var = $row['Forename'];
echo '<tr>';
echo '<td>' . $var . '</td>';
echo '<td>' . $row['Surname'] . '</td>';
echo "<td><a href='View.php?ID=" . urlencode($var) . "'><button type='button'>link</button></a></td>";
echo '</tr>';
}
echo '</tbody>';

Group rows from SQL database by date in tables

UPDATE - Added query
I am developing a system which gathers results from games from a MySQL database. I'd like the results to be 'grouped' by the date (e.g. results from a certain date will be in one table).
I'm nearly there, but struggling to get the results from the same date to display as the next row of the table.
.
Here's the code as it stands:
$result = mysqli_query($con, "SELECT `MatchDate`, t1.`TeamName` AS HomeTeam, `MatchHomeScore`, `MatchAwayScore`, t2.`TeamName` AS AwayTeam `FROM `match` INNER JOIN `team` t1 ON `match`.`MatchHomeTeamID` = t1.`TeamID` INNER JOIN `team` t2 ON `match`.`MatchAwayTeamID` = t2.`TeamID` ORDER BY `MatchDate` ASC ");`
$currentDate = false;
while($row = mysqli_fetch_array($result))
{
echo '<div class="col-lg-4">';
echo '<div class="panel panel-default-fixtures">';
if ($row['MatchDate'] != $currentDate){
echo '<div class="panel-heading">';
echo '<h4 class="panel-title">';
echo $row['MatchDate'];
echo '</h4>';
echo '</div>';
$currentDate = $row['MatchDate'];
}
echo '<table width="100%" class="table table-striped table-bordered table-hover dataTables">';
echo '<thead>';
echo '<tr>';
echo '<th class="all">';
echo 'Home';
echo '</th>';
echo '<th colspan="2">';
echo 'Score';
echo '</th>';
echo '<th class="all">';
echo 'Away';
echo '</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
echo '<tr>';
echo '<td>'.$row['HomeTeam'].'</td>';
echo '<td>'.$row['MatchHomeScore'].'</td>';
echo '<td>'.$row['MatchAwayScore'].'</td>';
echo '<td>'.$row['AwayTeam'].'</td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
echo '</div>';
echo '</div>';
}
2nd update
Used the code Shamil Omarov provided and fixed the issue with a few changes. Here's the working code:
$result = mysqli_query($con, "
SELECT `MatchDate`, t1.`TeamName` AS HomeTeam, `MatchHomeScore`, `MatchAwayScore`, t2.`TeamName` AS AwayTeam
FROM `match`
INNER JOIN `team` t1 ON `match`.`MatchHomeTeamID` = t1.`TeamID`
INNER JOIN `team` t2 ON `match`.`MatchAwayTeamID` = t2.`TeamID`
-- WHERE YEAR(`MatchDate`) =2017
ORDER BY `MatchDate` ASC ");
$currentDate = false;
while($row = mysqli_fetch_array($result))
{
if ($row['MatchDate'] != $currentDate){
if ($currentDate != false){
echo '</tbody>';
echo '</table>';
// /.table-responsive
echo '</div>';
// /.panel
echo '</div>';
// /.col-lg-4
}
echo '<div class="col-lg-4">';
echo '<div class="panel panel-default-fixtures">';
echo '<div class="panel-heading">';
echo '<h4 class="panel-title">';
echo $row['MatchDate'];
echo '</h4>';
echo '</div>';
echo '<table width="100%" class="table table-striped table-bordered table-hover dataTables">';
echo '<thead>';
echo '<tr>';
echo '<th class="all">';
echo 'Home';
echo '</th>';
echo '<th colspan="2">';
echo 'Score';
echo '</th>';
echo '<th class="all">';
echo 'Away';
echo '</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
$currentDate = $row['MatchDate'];
}
if ($row['MatchHomeScore'] != null && $row['MatchAwayScore'] != null){
echo '<tr class="success">';
} else {
echo '<tr>';
}
echo '<td>'.$row['HomeTeam'].'</td>';
echo '<td>'.$row['MatchHomeScore'].'</td>';
echo '<td>'.$row['MatchAwayScore'].'</td>';
echo '<td>'.$row['AwayTeam'].'</td>';
echo '</tr>';
}
This new code now outputs:
check this.
$currentDate = false;
while($row = mysqli_fetch_array($result))
{
echo '<div class="col-lg-4">';
echo '<div class="panel panel-default-fixtures">';
if ($row['MatchDate'] != $currentDate){
if($currentDate != false){
echo '</tbody>';
echo '</table>';
echo '</div>';
echo '</div>';
}
echo '<div class="panel-heading">';
echo '<h4 class="panel-title">';
echo $row['MatchDate'];
echo '</h4>';
echo '</div>';
echo '<table width="100%" class="table table-striped table-bordered table-hover dataTables">';
echo '<thead>';
echo '<tr>';
echo '<th class="all">';
echo 'Home';
echo '</th>';
echo '<th colspan="2">';
echo 'Score';
echo '</th>';
echo '<th class="all">';
echo 'Away';
echo '</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
$currentDate = $row['MatchDate'];
}
echo '<tr>';
echo '<td>'.$row['HomeTeam'].'</td>';
echo '<td>'.$row['MatchHomeScore'].'</td>';
echo '<td>'.$row['MatchAwayScore'].'</td>';
echo '<td>'.$row['AwayTeam'].'</td>';
echo '</tr>';
}
I think you need to change the query. Could you show it in order to find out what is needed to be changed?

return a row and avoid null fields inside of it

How to return a row into table form and avoid fields that are null?
<?php
$o = mysqli_query("SELECT * FROM orders ORDER BY po_number DESC LIMIT 1");
echo 'The Following Order Information has been submited.';
echo '<table width="70%" border="5" align="center">';
while($row = mysqli_fetch_array($o)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
use array_filter($row) before foreach(). It removes all empty elements from array().
echo 'The Following Order Information has been submited.';
echo '<table width="70%" border="5" align="center">';
while($row = mysqli_fetch_array($o)) {
$row = array_filter($row); //This line
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
echo '</table>';
foreach($row as $field) {
if(isset($field) && !empty($field)) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}

Set background color of cells based on MySQL query output

I am new to PHP and trying to learn enough to do some basic functions. I've been able to create a table for my users to edit themselves, and redisplay but I've come across a question.
Using the script below, users can input their skill level for various products. I wanted to be able to highlight each cell in which they input "0" or blank. User's input will be between 0-5 (or blank if they haven't filled it in yet).
This is all being done on my localhost so I'll admit all the security measures are not quite there.
I've read a lot of posts and tried to figure it out myself, but I'm doing something fundamentally wrong I believe.
Any assistance on this would be greatly appreciated. I've been known to buy a beer (via paypal) for those who help me with coding :)
Here is my existing code for printing out the results of the database:
<?php
//This will connect to the database in order to begin this page
mysql_connect("localhost", "root", "time2start") or die (mysql_error());
//Now we will select the database we need to talk to
mysql_select_db("joomla_dev_15") or die (mysql_error());
$query = "SELECT * FROM enterprise_storage WHERE id=1";
$result = mysql_query($query) or die (mysql_error());
echo "<table border='1'>";
echo "$row";
echo "<tr> <th>Product</th> <th>Wayne Beeg</th> <th>Paul Hamke</th> <th>Steve Jaczyk</th> <th>David Jontow</th> <th>Ed MacDonald</th> <th>Michael Munozcano</th> <th>Ron Shaffer</th> <th>Luke Soares</th> <th>Josh Wenger</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['model'];
echo "</td><td>";
echo $row['beeg'];
echo "</td><td>";
echo $row['hamke'];
echo "</td><td>";
echo $row['jaczyk'];
echo "</td><td>";
echo $row['jontow'];
echo "</td><td>";
echo $row['macdonald'];
echo "</td><td>";
echo $row['munozcano'];
echo "</td><td>";
echo $row['shaffer'];
echo "</td><td>";
echo $row['soares'];
echo "</td><td>";
echo $row['wenger'];
echo "</td></tr>";
}
echo "</table>";
?>
<FORM>
<INPUT TYPE="BUTTON" VALUE="Return to the Home Page" ONCLICK="window.location.href='http://localhost/~user/joomla15/custom/skilldisplay.php'">
</FORM>
Maybe
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr>";
foreach($row as $content) {
if($content == 0) {
echo "<td style='background-color:gray;'>";
}
else {
echo "<td style='background-color:green;'>";
}
echo $content . "</td>";
}
echo $row['wenger'];
echo "</td>";
}
echo "</tr></table>";
try something like this
add this to of your generated document
<style type="text/css">
.red{ background-color: red; }
</style>
This is your PHP:
<?php
// sanitize value
$value = trim($row['model']);
$class = (empty($value)) ? 'red' : '';
// display
echo "<td class=\"$class\">$value</td>";
...
?>
Ok, so I managed to get it working finally. The two replies above helped me figure out the right approach to doing this.
Of course, my approach may not be the best method, but I've tested it and it works for my needs. For any future searchers, here's what I did:
<?php
//This will connect to the database in order to begin this page
mysql_connect("localhost", "root", "time2start") or die (mysql_error());
//Now we will select the database we need to talk to
mysql_select_db("joomla_dev_15") or die (mysql_error());
$query = "SELECT * FROM enterprise_storage";
$result = mysql_query($query) or die (mysql_error());
echo "<table border='1'>";
echo "$row";
echo "<tr> <th>Product</th> <th>Wayne Beeg</th> <th>Paul Hamke</th> <th>Steve Jaczyk</th> <th>David Jontow</th> <th>Ed MacDonald</th> <th>Michael Munozcano</th> <th>Ron Shaffer</th> <th><a href='http://localhost/~user/joomla15/custom/updateform.php'>Luke Soares</a></th> <th>Josh Wenger</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['model'];
echo "</td>";
if ($row['beeg'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['beeg'] ;
}else{
echo '<td>' .$row['beeg'];
}
echo "</td>";
if ($row['hamke'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['hamke'] ;
}else{
echo '<td>' .$row['hamke'];
}
echo "</td>";
if ($row['jaczyk'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['jaczyk'] ;
}else{
echo '<td>' .$row['jaczyk'];
}
echo "</td>";
if ($row['jontow'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['jontow'] ;
}else{
echo '<td>' .$row['jontow'];
}
echo "</td>";
if ($row['macdonald'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['macdonald'] ;
}else{
echo '<td>' .$row['macdonald'];
}
echo "</td>";
if ($row['munozcano'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['munozcano'] ;
}else{
echo '<td>' .$row['munozcano'];
}
echo "</td>";
if ($row['shaffer'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['shaffer'] ;
}else{
echo '<td>' .$row['shaffer'];
}
echo "</td>";
if ($row['soares'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['soares'] ;
}else{
echo '<td>' .$row['soares'];
}
echo "</td>";
if ($row['wenger'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['wenger'] ;
}else{
echo '<td>' .$row['wenger'];
}
echo "</td></tr>";
}
echo "";
?>

Categories