PHP sorting by column header issue - php

I am having an issue sorting my datatable by the column header.
I have a build-query mechanism on my site that can take in 1 or more values the user selects. The values get turned into PHP variables that then get passed into the query and prints out the datatable to the screen. The address bar URL is updated as well.
I want to be able to sort by the column headers of the table.
I will show you the PHP code bypassing the whole build-query function. I'll start right at the SORT portion and the query:
<?php
if ($_GET['sort'] == "") {
$sort_by = "BOL_NUMBER";
} else {
$sort_by = $_GET['sort'];
}
$select = "";
if ($_SESSION['where'] != "") {
$select = "SELECT * FROM `mainTable` WHERE (". $_SESSION['where'] . ") ORDER BY " . $sort_by . "";
}
// $_SESSION['where'] comes from the build query and can contain 1 or more values
$QueryResult = mysql_query($select) or die ();
$resnum = mysql_num_rows($QueryResult);
This next part is where the table gets populated:
if ($resnum == 0) {
echo "no results";
} else {
echo "<table>\n";
echo "<thead><tr>" .
"<th>BOL</th>" .
"<th>CONTAINER</th>" .
"<th>LOCATION</th>" .
"<th>STATUS</th>" .
"</tr></thead><tbody>\n";
while(($Row = mysql_fetch_assoc($QueryResult)) !== FALSE) {
echo "<tr>";
echo "<td>{$Row[BOL_NUMBER]}</td>";
echo "<td>{$Row[CONTAINER_NUMBER]}</td>";
echo "<td>{$Row[LOCATION_CITY]}</td>";
echo "<td>{$Row[STATUS_TYPE]}</td>";
echo "</tr>";
}
echo "</tbody></table>\n";
?>
There are many more columns. I just picked a couple.
I found this page for this next part:
Sorting html table with a href and php from sql database
So I tried to apply what I read in the link to the headers, like this:
"<th><a href='myPage.php?sort=BOL_NUMBER'>BOL</a></th>" .
"<th><a href='myPage.php?sort=CONTAINER_NUMBER'>CONTAINER</a></th>" .
"<th><a href='myPage.php?sort=LOCATION_CITY'>LOCATION</a></th>" .
"<th><a href='myPage.php?sort=STATUS_TYPE'>STATUS</a></th>" .
Now, I can click on the column headers, but when I do, it does not keep the user's selection and I can tell because the URL changes like this example below:
(this is just an example. it does not include the parameters in the table above)
(just keep note of the &sort in this url)
http://home.someCompany.com/myAPP/mypage.php?direction=I&type=&submit=Go&city=&pod=&terminal=&ramp=&container=&bol=&voyage=&conStatus=&con_location=&sort=&status=
Will change to this (if I select the header for CONTAINER):
http://home.someCompany.com/myAPP/mypage.php?&sort=CONTAINER_NUMBER
When this happens, the datatable is no longer on the screen. It's like it removes everything from the query and just adds the sort. But there is now nothing to sort.

The $_SERVER['QUERY_STRING'] superglobal variable give you access to the GET parameters. By using it you can keep the current parameters of the request.
So by changing your link by this :
$urlQuery = str_replace(array('&sort=BOL_NUMBER', '&sort=CONTAINER_NUMBER', '&sort=LOCATION_CITY', '&sort=STATUS_TYPE'), '', $_SERVER['QUERY_STRING']); // To clean previous sorting, maybe replace by a regex
"<th><a href='myPage.php?' . $urlQuery . '&sort=BOL_NUMBER'>BOL</a></th>" .
"<th><a href='myPage.php?' . $urlQuery . '&sort=CONTAINER_NUMBER'>CONTAINER</a></th>" .
"<th><a href='myPage.php?' . $urlQuery . '&sort=LOCATION_CITY'>LOCATION</a></th>" .
"<th><a href='myPage.php?' . $urlQuery . '&sort=STATUS_TYPE'>STATUS</a></th>" .
You should reach your goal.

Related

Pagination script doesn't work with datatables

I've been dealing with tihs problem for more than two days but still couldn't find what's the problem. I am trying to build a pagination system for my search results. Code works perfectly fine when I run it in new php file but when it comes to display those result in a table I constantly keep getting that Error! message inside of the last else section. Plus, wherever I place for loop for page numbers it always showing before the table. Think I was so busy with dealing with this problem I am focusing to the same point. Help, please!
edit I've just deleted all conditional statements and got undefined index for all my variables that I get by POST method. That's the problem but still don't know what might be the solution for this.
<?php
if (isset($_POST['search_btn'])) {
include_once "db_connect.php";
$from = $_POST['from'];
$where = $_POST['where'];
$date = $_POST['date'];
$type = $_POST['type'];
$proc_id = $_POST['proc_id'];
if(empty($from) || empty($where) || empty($date) || empty($type)){
header("Location: index.php?search=empty");
exit();
}else{
//define how many results you want per page
$results_per_page = 10;
//number of results stored in database
"SELECT * FROM proc WHERE p_from = '".$from."' and p_where = '".$where."' and type= '".$type."' ";
$result = mysqli_query($conn, $sql);
$number_of_results = mysqli_num_rows($result);
//determine number of total pages available
$number_of_pages = ceil($number_of_results/$results_per_page);
//determine which page number visitor is currently on
if (!isset($_GET['page'])) {
$page = 1;
} else {
$page = $_GET['page'];
}
//determine the SQL LIMIT starting number for the result on the displaying page
$this_page_first_result = ($page-1)*$results_per_page;
//retrive selected results from database and display them on page $sql='SELECT * FROM proc LIMIT ' . $this_page_first_result . ',' . $results_per_page;
$result = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<tr onclick="content(\''. $rows['proc_id'] .'\')">';
echo "<td>" .$rows['p_name'] . " " . $rows['p_surname']. " </td>";
echo "<td>" .$rows['p_from']. "</td>";
echo "<td>" .$rows['p_where']. "</td>";
echo "<td>" .$rows['p_date']. "</td>";
echo "<td>" .$rows['price']. "</td>";
echo "<td>" .$rows['type']. "</td>";
echo "</tr>";
}
}
//display the links to the pages
for ($page=1;$page<=$number_of_pages;$page++) {
echo '' . $page . ' ';
}
}else{
echo "Error!";
}
?>
I'm just going to assume that the initial display works, but that pagination is giving you problems?
You're using POST values to pass the data from the search form to your code, however, when you then click the pagination links you are transferred to the search page, and lose those values.
You could change the next page URL to be a form and you pass each necessary value as a hidden input field. However, this has the drawback that when you hit the back button in your browser that it'll complain and ask you to resubmit the form data.
Another solution would be to store these post params in a session, cookie, whatever really. But in my opinion, that's not too great of a solution for this issue either.
I'd suggest you use GET parameters and then pass those in the next page button as well. This has the added benefit of being able to bookmark your searches.
Good luck!
As a side note, instead of building your query using concatenation you should use prepared statements. See the docs for the functions I used in the converted code below: https://www.php.net/manual/en/class.mysqli-stmt.php
if ($statement = mysqli_prepare($conn, "SELECT * FROM proc WHERE p_from = ? AND p_where = ? AND type = ?")) {
mysqli_stmt_bind_param($statement, "s", $from);
mysqli_stmt_bind_param($statement, "s", $where);
mysqli_stmt_bind_param($statement, "s", $type);
$result = mysqli_stmt_get_result($statement);
}

Inserting wrong data in to the database with $wpdb->insert

So hey guys!
I currently have a code that gets data from a custom table called wp_refundrequests, and prints them as a table to the page. On the page the admin can either Accept, or Deny the request by pressing a button on the side of each order. Denying the request just deletes the request from the table, but accepting should delete it from the current table and insert the information to the next table called "accepted requests".
The wp_refundrequests table contains customer's order that they want to refund.
The code that gets the info and prints it:
global $wpdb;
$requests = $wpdb->get_results("SELECT * FROM wp_refundrequests", ARRAY_A);
foreach ($requests as $row) {
echo "<div class='requests'>" . "<li class='refunds'>" . "Palauttajan nimi: ".
$row['customer_name'] . "</br>" ."Palautettavat tuotteet: ".$row['product_name']."<br> "."Määrä: ".
$row['product_qty'] . " "
. "<br>Kommentti: " . $row['comment'] . "<br> " . "Hinta: " . $row['refund_total'] . "€ " .
"<br>" . "Päivämäärä: " . $row['request_date'] . " " .
"<a class='right' href='admin-page?deleteid=" . $row['request_id'] . "'>Deny</a></li>" .
"<li class='refundaccepts'><a href='admin-page?acceptid=" . $row['request_id']
. "'>Accept</a></li>" . "</div>";
$_SESSION['custname'] = $row['customer_name'];
$_SESSION['prodname'] = $row['product_name'];
}
With my current code, the "Accept" button deletes it, and inserts information in to the new table, BUT the information that is inserted is wrong. It seems like it wants to either insert the latest data that had been inserted in to the wp_refundrequests table to the wp_acceptedrequests, or it keeps the data from the latest refund request and tries to insert that instead because for example as seen here(Sorry for the bits of Finnish as well):
If I were to click the "Accept" button on the above, older one, the query would still insert it like this:
So it basically inserts the info from the latest refund_request insert and inserts that instead of the one selected. However the one that had been selected still gets deleted from the table.
Here's the code that is triggered when the user clicks on "Accept"
$custname = $_SESSION['custname'];
$prodname = $_SESSION['prodname'];
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
/* Query to do whatever here */
$wpdb->print_error();
$wpdb->insert("wp_acceptedrequests", [
"customer_name" => "$custname",
"name_product" => "$prodname",
"date" => date("Y/m/d/G:i:sa") ,
]);
$wpdb->print_error();
$wpdb->query("DELETE FROM wp_refundrequests WHERE request_id = $accept");
}
I have to say I have no idea why it doesn't want to insert the selected request, please comment if there's something confusing, I'll try to clear it up then.
Thanks in advance!
You redefine $_SESSION with in foreach loop so at the end of foreach it will equal to the last one, pass each row parameter to it is accept link like this
"<li class='refundaccepts'><a href='admin-page?acceptid=" . $row['request_id']."&custname=".$row['customer_name']."&prodname=".$row['product_name']."'>Accept</a></li></div>";
Then call it the same way you get $accept-ID
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
$custname = $_GET['custname'];
$prodname = $_GET['prodname'];
Note:Iuse my phone so make sure if it was a syntax error in the href part of the code
Please try like this and comment out the session variable.
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
$accepted_requests = $wpdb->get_results("SELECT * FROM wp_refundrequests WHERE id = $accept", ARRAY_A);
if( !empty($accepted_requests) ) {
$insert = $wpdb->insert("wp_acceptedrequests", $accepted_requests);
if($insert) {
$wpdb->query("DELETE FROM wp_refundrequests WHERE request_id = $accept");
}
}
}

Finding pattern according to variable content

I would like to do something quite simple but I dont know the right code in php.
I have a variable $go which content is GO:xxxxx
I would like to query that if the content of a variable has the pattern "GO:" and something else, echo something, but if not, echo another thing
I want to declare an if statement like:
if (preg_match('/GO/', $go) {
echo "something";
}
else {
echo "another thing";
But I cannot make it work...
I want to embed this statement between this portion of my script:
$result = mysqli_query($enlace,"select count(distinct name2) as total from " . $table . " where go_id like '%" . $go . "%'");
$items = mysqli_fetch_assoc($result);
echo "<br/>";
echo "<b> The total number of genes according to GO code is:</b> " . $items['total'];
mysqli_free_result($result);
$result2 = mysqli_query($enlace,"select count(distinct name2) as total from " . $table . " where db_object_name like '%" . $go . "%'");
$items2 = mysqli_fetch_assoc($result2);
echo "<br/>";
echo "<b>The total number of genes according to GO association is:</b> " . $items2['total'];
mysqli_free_result($result2);
As it is right now, the variable $go can have a value like GO:xxxx or a random sentence, and, with this code, I get two strings, one with value 0 and another with value according to the total apperances matching $go content.
What I want is to declare an if statement so that it just prints one string, the one that has the number of matches according to $go content, but not both.
Any help?
Use strpos():
if (strpos($go, 'GO:') !== false) {
echo 'true';
}
Try this
echo (!strpos($go, 'GO:')) ? "another thing" : "something";
Will surely work

How can I use hyperlinks in PHP to display data on the page it sends you to?

I have this piece of code below. It displays the image and name of all the entries in a table in my database. The name is set up to become a hyperlink.Is it possible to make it so when one specific name is clicked that data for only that specific name will be displayed on the page you are sent to?
So for example if I select the first entry that is displayed back "mealname1" and it takes me to the showrecipe.php page, can I make it so I can display all the data I have for "mealname1" and only "mealname1". I'm really lost, I have scoured the internet and my php books but can't find anything to that is relevant.
If there is no way of doing it is there an obvious solution that I am missing?... I am very much a novice to this... thanks for your help guys.
<?php
require("db.php");
$prodcatsql = "SELECT * FROM recipes";
$prodcatres = mysql_query($prodcatsql);
$numrows = mysql_num_rows($prodcatres);
if($numrows == 0)
{
echo "<h1>No Products</h1>";
echo "There are no recipes available right now.";
}
else
{
echo "<table id='recipetable'>";
while($prodrow = mysql_fetch_assoc($prodcatres))
{
echo "<tr>";
if(empty($prodrow['image'])){
echo "<td><img
src='./images/No_image.png' alt='"
. $prodrow['mealname'] . "'></td>";
}
else {
echo "<td><img src='./images/".$prodrow['image']
. "' alt='"
. $prodrow['mealname'] . "'></td>";
}
echo "<td>";
echo ''.$prodrow['mealname'].'';
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
Change the query to
SELECT * FROM recipes WHERE mealname='$mealname' LIMIT 1;
You can remove "LIMIT 1" if you want but this makes sure you will only get 1 or 0 row back. Don't forget to escape the string.

How to create a numbered list inside a table with PHP

I'm executing this type of code inside a table.
while($row = mysql_fetch_array($result))
{
echo "" . $row['id'] . "";
echo "" . $row['name'] . "";
echo "" . $row['car'] . "";
}
Which works great and gives me a numbered list (1 Mike Volvo, 2 Mike Ford) for example. The problem is that I now have multiple users in the same table so there are gaps in the list where someone else's entry is since i'm using auto incremented ID for numbers.
So assuming I have 5 entries I obviously want it to be 1-5 but right now its 5-30-45-65 or whatever.
Anyway I looked around for a solution and I found $number = 1; $number++; to be effective and it kind of works and gives me a 1-5 list independent of whatever the ID's are.
The problem is that when I reverse the list using ORDER BY xxx desc the last entry becomes 1 and the first entry becomes 5. But I always want the first entry to remain 1 and the last entry to be 5.
Do you have any ideas on how to create this function using PHP?
You need to simple user $number as you mentioned as in the following code
$number = 1;
while($row = mysql_fetch_array($result))
{
echo $number;
echo "" . $row['name'] . "";
echo "" . $row['car'] . "";
++$number;
}
Even if in your SQL you have order by it does not matter in that case.
From what I understand of your question... You are on the right track using the following code...
$LastId ='';
$number = 0;
while($row = mysql_fetch_array($result))
{
if($LastId != $row['id']){
$number++;
}
echo $number;
echo "" . $LastId = $row['id'] . "";
echo "" . $row['name'] . "";
echo "" . $row['car'] . "";
}
So...
If the 'id' isn't the same as the last 'id' (not the same user) it will increment it by 1. Otherwise it will stay the same.
Hope this is what you looking for and helps.
Although this is pretty trivial in php, I would not use php for it. You can easily do this in html:
echo "<ol>";
while($row = mysql_fetch_array($result))
{
echo "<li>" . $row['name'] . $row['car'] . "</li>";
}
echo "</ol>";

Categories