Sort a HTML Table Column that Contains SQL Data - php

I'm creating a simple transactions report page that takes inputted database data and displays it on an HTML table. I want to be able to sort each column on the client side in asc/desc order when the table header is clicked upon, but I can't get my functions to work.
<?php session_start();
include 'db.php';
include 'head.php';
$sql = "SELECT * FROM ach";
$result = $mysqli->query($sql);
echo "<div class='w3-row-padding w3-margin'>";
if ($result->num_rows) {
echo "<table class='w3-table-all'>
<thead>
<tr>
<th><a href='transactions.php?sort=submittedDate'>Submitted Date</a></th>
<th><a href='transactions.php?sort=accountNumber'>Chief Account Number</a></th>
<th><a href='transactions.php?sort=accountHolderName'>Account Holder</a></th>
<th><a href='transactions.php?sort=achAccountType'>Account Type</a></th>
<th><a href='transactions.php?sort=transferType'>Transfer Type</a></th>
<th><a href='transactions.php?sort=recurringMonthlyTransferDate'>Transfer Date</a></th>
<th><a href='transactions.php?sort=status'>Status</a></th>
<th> </th>
</tr>
</thead>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tbody><tr><td>".$row["submitDate"]."</td><td>".$row["accountNumber"]."</td><td>".$row["accountHolderName"]."</td><td>".$row["achAccountType"]."</td><td>".$row["transferType"]."</td><td>".$row["recurringMonthlyTransferDate"]."</td><td>".$row["status"]."</td><td>Review</td></tr></tbody>";
}
echo "</table>";
} else {
echo "0 results";
}
echo "</div>";
if ($_GET['sort'] == 'submittedDate')
{
$sql .= " ORDER BY `ach`.`submitDate` ASC ";
}
elseif ($_GET['sort'] == 'accountNumber')
{
$sql .= " ORDER BY accountNumber";
}
elseif ($_GET['sort'] == 'accountHolderName ')
{
$sql .= " ORDER BY accountHolderName ASC";
}
elseif($_GET['sort'] == 'achAccountType')
{
$sql .= " ORDER BY achAccountType";
}
elseif($_GET['sort'] == 'transferType')
{
$sql .= " ORDER BY transferType";
}
elseif($_GET['sort'] == 'recurringMonthlyTransferDate')
{
$sql .= " ORDER BY recurringMonthlyTransferDate";
}
elseif($_GET['sort'] == 'status')
{
$sql .= " ORDER BY status";
}
$mysqli->close();
include 'foot.php';
?>

You must add your sorting statements BEFORE you execute the query. Query is executed on this line:
$result = $mysqli->query($sql);

If you want to sort data at server end you have to use order by clause. If you want jquery to sort at client end you can use Data tables
Also put <tbody> </tbody> outside the while. your table is having many tbody tags as there are many rows.
$sort = "";
if(isset($_GET["sort"])) {
$sort = $_GET["sort"];
//validate that it is real column name so that you will not get any error
if(!in_array($sort, array("submittedDate", "accountNumber", "accountHolderName", "achAccountType", "transferType", "recurringMonthlyTransferDate", "status"))) {
$sort = "";
}
if($sort !="") {
$sort = " order by ".$sort." ASC";
}
}
$sql = "SELECT * FROM ach".$sort;

Related

How do I display different table from 1 table? Like each table has unique code

This are my db table:
But my query only get 1 row for each table like this:
As you can see, there are 2 tables for 1003 because it has 2 rows. It should be only one (1) table of 1003 with 2 rows. How do I fix this? EXPECTED RESULT:
// Attempt select query execution
$query = "SELECT model, brand_code FROM smartphone GROUP BY model";
if($result = mysqli_query($db, $query))
{
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<?php echo $row["brand_code"]?>
<table id="table_stock" class="">
<thead>
<tr>
<th>Model</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $row["model"]?></td>
</tr>
</tbody>
</table><br>
<?php
}
/// Free result
mysqli_free_result($result);
}
else
{
echo "<td class='no_record' colspan='7'>No records found.</td>";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
You have at least 5 problems here,
[edit: problem 1 removed & changed sample based on extended answer]
Inside your while { ... } loop, you're printing an entire table, when you should only be printing the <tr>...</tr> part there. This is what causes additional table(s).
And 3rd problem: your "no_record" line is a loose <td>. Not only isn't it inside the table (which is covered in problem #2), it's also not wrapped with a <tr>.
4th problem: You're randomly printing the echo $row["brand_code"] outside of the table.
5th problem: you're printing raw data from the database as if it is valid html, it more than likely is not. it has to be probably encoded with htmlentities/htmlspecialchars.
Quick & dirty fixed version:
function tableOpen($row) {
printf( '<h1>%s</h1>', htmlentities($row["brand_code"]) );
echo '<table id="table_stock" class="">';
echo '<thead>';
echo '<tr>';
echo '<th>Model</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
}
function tableClose() {
echo '</tbody>';
echo '</table><br>';
}
// Attempt select query execution
$query = "SELECT model, brand_code FROM smartphone ORDER BY brand_code";
$lastBrand = null;
if ($result = mysqli_query($db, $query)) {
if (mysqli_num_rows($result) > 0) {
if ($lastBrand !== $row["brand_code"] && !is_null($lastBrand)) tableClose();
if ($lastBrand !== $row["brand_code"]) tableOpen($row);
$lastBrand = $row["brand_code"];
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
printf( '<td>%s</td>', htmlentities($row["model"]) );
echo '</tr>';
}
tableClose();
/// Free result
mysqli_free_result($result);
} else {
echo '<p class="no_record">No records found.</p>';
}
} else {
echo "ERROR: Not able to execute \$query: <br>" . htmlentities($query) . '<br>' . htmlentities(mysqli_error($link));
}
you need additional loop. Also in the first query you need to use group by codes.
$query = "SELECT model, brand_code FROM smartphone GROUP BY brand_code";
if($result = mysqli_query($db, $query))
{
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<?php echo $row["brand_code"]?>
<table id="table_stock" class="">
<thead>
<tr>
<th>Model</th>
</tr>
</thead>
<tbody>
<?php
if ($result1 = mysqli_query($db, "SELECT DISTINCT model, brand_code FROM smartphone WHERE brand_code={$row["brand_code"]}"))
{
while ($row1 = mysqli_fetch_array($result1))
{
// get count for each model within brand_code
$cnt = ($result2 = mysqli_query($db, "SELECT COUNT(*) AS cnt FROM smartphone WHERE brand_code={$row["brand_code"]} AND model='{$row1["model"]}'")) && ($row2 = mysqli_fetch_array($result2)) ? $row2["cnt"] : "---";
?>
<tr>
<td><?php echo $row1["model"] ({$cnt})?></td>
</tr>
<?php
}
mysqli_free_result($result1);
}
?>
</tbody>
</table><br>
<?php
}
/// Free result
mysqli_free_result($result);
}
else
{
echo "<td class='no_record' colspan='7'>No records found.</td>";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

I wanted to display sortable tables on my page but it returns no recods and i cannot see where is the problem

I wanted to display sortable tables on my page but it returns no records and I cannot see where is the problem
<?php
$mysqli = new MySQli('localhost', 'root', '', 'statystyki');
if (isset($_GET['order'])) {
$order = $_GET['order'];
} else {
$order = 'ID';
}
if (isset($_GET['sort'])) {
$sort = $_GET['sort'];
} else {
$sort = 'ASC';
}
$resultSet = $mysqli->query("SELECT ID, Gracz FROM rank ORDER BY $order $sort");
if ($resultSet->num_rows > 0) {
$sort == 'DESC' ? $sort = 'ASC' : $sort = 'DESC';
echo "
<table border='1'>
<tr>
<th><a href='?order=ID&&sort=$sort'>ID</a></th>
<th><a href='?order=sn&&sort=$sort'>Gracz</a></th>
";
while ($rows = $resultSet->fetch_assoc()) {
$ID = $rows['ID'];
$sn = $rows['Gracz'];
echo "
<tr>
<td>$ID</td>
<td>$sn</td>
</tr>
";
}
echo "
</table>
";
} else {
echo "No records";
}
What is solution?

PHP: No output from $row variable even if it is already defined

I don't know why it doesn't show up anything, I already tested my query and it is working in my phpmyadmin, but in my php code it does not work upon adding the AS keyword. My goal for this is to place a value to a variable coming from the SUM() keyword.
<?php
require_once "user-connect.php";
$user = $_SESSION['id'];
$sql = "SELECT SUM(total) AS sumz FROM cart WHERE userID = $user AND month(orderDate) = month(now()) AND day(orderDate) = day(now())";
$result = $link->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo $row['sumz'];
}
if (mysqli_query($link, $sql)) {
} else {
echo "Error: " . $sql . "" . mysqli_error($link);
} ?>
<table cellspacing="0">
<tbody>
<tr class="cart-subtotal">
<th>Cart Subtotal</th>
<td><span class="amount"><?php echo $row['sumz']; ?></span></td>
</tr>
You can use:
$sql = "SELECT SUM(total) FROM cart WHERE..."
And in HTML:
<td><span class="amount"><?php echo $row['SUM(total)']; ?></span></td>
Take a look at PHP fetch assoc guide.
while ($row = $result->fetch_assoc()) {
echo $row['sumz'];
}
An example of getting the SUM value
<?php
$sql="SELECT sum(amount) as total FROM table";
$result = mysqli_query($sql);
while ($row = mysqli_fetch_assoc($result)) {
echo $row['total'];
}
mysqli_close($con);
?>

User List creates duplicates?

I've made this code using a tutorial that allows me to upload users to the database. The whole thing works great, but the only problem is that it starts to show 2 of the same user over and over, the list starts expanding 5 every user i add... What could be the problem causing this?
Item in index that lays out the whole list:
<h2>Names:</h2>
<table border='1'>
<tr>
<th>ID</th>
<th>Username</th>
</tr>
<?php
$sql_list = "SELECT * FROM names ORDER BY username ASC";
$results = mysqli_query($db, $sql_list) or die(mysql_error());
$names = "";
if(mysqli_num_rows($results) > 0) {
while($row = mysqli_fetch_assoc($results)) {
$id = $row['id'];
$user = $row['username'];
$names .= "<tr><td>$user</td></tr>";
echo $names;
}
} else {
echo "No Users Found";
}
?>
</table>
Either output the one record per iteration; or build the whole HTML block, then output the block. I think the simplest would be:
while($row = mysqli_fetch_assoc($results)) {
$id = $row['id'];
$user = $row['username'];
echo "<tr><td>$user</td></tr>";
}
... alternative approach
<h2>Names:</h2>
<table border='1'>
<tr>
<th>ID</th>
<th>Username</th>
</tr>
<?php
$sql_list = "SELECT * FROM names ORDER BY username ASC";
$results = mysqli_query($db, $sql_list) or die(mysqli_error($db));
$names = "";
if(mysqli_num_rows($results) > 0) {
while($row = mysqli_fetch_assoc($results)) {
$id = $row['id'];
$user = $row['username'];
$names .= "<tr><td>$user</td></tr>";
}
} else {
$names = "No Users Found";
}
echo $names;
?>
</table>
Also you can't use mysql_* functions with mysqli_*. See http://php.net/manual/en/mysqli.error.php.
Simplest example of the issue: https://eval.in/627250

Unable to sort with date

Im trying to order posts by their date, but whenever I try to do that I get this error:
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\localhost\bootstrap\category.php on line 58
DATABASE STRUCTURE: http://puu.sh/1630b
<?php
//category.php
include 'connect.php';
//first select the category based on $_GET['cat_id']
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories
WHERE
cat_id = " . mysql_real_escape_string($_GET['id']);
$result = mysql_query($sql);
if(!$result)
{
echo 'The category could not be displayed, please try again later.' . mysql_error();
}
else
{
if(mysql_num_rows($result) == 0)
{
echo 'This category does not exist.';
}
else
{
//display category data
while($row = mysql_fetch_assoc($result))
{
echo '<h2>Topics in ′' . $row['cat_name'] . '′ category</h2><br />';
$title = $row['cat_name'];
include 'header.php';
}
//do a query for the topics
$sql = "SELECT
topic_id,
topic_subject,
topic_date,
topic_cat
FROM
topics
ORDER BY
topic_date DESC
WHERE
topic_cat = " . mysql_real_escape_string($_GET['id']);
$result = mysql_query($sql);
// if(!$result)
// {
// echo 'The topics could not be displayed, please try again later.';
// }
// else
// {
if(mysql_num_rows($result) == 0)
{
echo 'There are no topics in this category yet.';
}
else
{
//prepare the table
echo '<table border="1" class="table table-bordered table-striped" style="float: right; width: 990px;">
<tr>
<th>Topic</th>
<th>Created at</th>
</tr>';
while($row = mysql_fetch_assoc($result))
{
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3>' . $row['topic_subject'] . '<br /><h3>';
echo '</td>';
echo '<td class="rightpart">';
echo date('d-m-Y', strtotime($row['topic_date']));
echo '</td>';
echo '</tr>';
echo '';
echo '';
}
echo '</table>';
echo '</div>';
}
// }
}
}
include('footer.php');
?>
I this case the problem will be in the commented lines 52 - 57 which are supposed to check if the mysql_query has been successful. Your query fails and returns false (boolean), which is a valid return value.
The error itself depends on your database table structure (isn't part of your link).
Your query that executes, fails and returned a boolean instead of a resource!
build in some error handling in your script.
do not use mysql_ functions, they are deprecated.
And now that you have edited your post, it is obvious that the ORDER BY comes after the WHERE.

Categories