Pagination script doesn't work with datatables - php

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);
}

Related

Return Specific Row From DB

I have multiple links on a page where each link is suppose to return a specific row of data from a database. When the link is clicked, the user is forwarded to another page where the info associated with that link is displayed. Here is the code:
//db connection: (using xampp)
mysql_connect('localhost', 'root', '');
mysql_select_db('db_name');
$sql = "SELECT * FROM user_input";
$records = mysql_query($sql);
//code:
<div>
$open_report = mtsql_fetch_assoc($records);
echo "Error Report# {$open_report['id']};
echo "<p>" .$open_report['comments'] . "</p>";
</div>
The problem is it always returns the same row of data. Each row in the db is associated with a link and when that link is clicked I want to return the associated row of data in the db. I think it may have to do with this line: $sql = "SELECT * FROM user_input"; but I'm not sure how to fix it. If anyone can help it would be greatly appreciated.
I have restructured my answer to give it a better flow. I also noticed you are using mysql_ not mysqli_ . You need to use mysqli_ as mysql is depreciated.
EDIT: This would be the page that displays all the error reports. You would want to output them in the form of a hyperlink that passes a GET parameter to the page that shows the details.
$sql = "SELECT ID, Description, etc, etc from reports";
$open_reports = mysqli_query($sql);
//error check here as well if ANY results were returned
while($row = mysqli_fetch_array($open_reports, MYSQLI_ASSOC)) {
echo ''' . $open_reports['Description'] . '';
}
This will give you links that look like
detailspage.php?id=1 detailspage.php?id=2
etc...
On the "detailspage.php" You can capture that ID and display dynamic information on that same page.
if (isset($_GET['ID'])){
$sql = "Select * from user_input where ID='" . $_GET['id'] . "'";
$records = mysqli_query($sql)
while($open_report = mysqli_fetch_array($records, MYSQLI_ASSOC)) {
echo "Error Report# " . $open_report['id'] . "<br/>";
echo "<p>" .$open_report['comments'] . "</p>";
}
}

PHP sorting by column header issue

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.

PHP/MySQL OnClick Update MySQL

Need to update a hitcount field in a MySQL table when a user clicks on a banner ad. Have the random ad display script working but can't figure out how to update the table when they click..assuming will have to pass the ID to Ajax but no idea how to approach it? Code is below:
include 'connection.php';
$query = "select * from ads where adtype = 'small' and status = 'yes' ORDER BY RAND() LIMIT 3";
$result = mysql_query($query) or die(mysql_error());
$num_results = mysql_num_rows($result);
if ($num_results !="0")
{
for($i=0;$i<$num_results;$i++)
{
$row = mysql_fetch_array($result);
$client = htmlspecialchars(stripslashes($row['client']));
$link = htmlspecialchars(stripslashes($row['link']));
$filename = htmlspecialchars(stripslashes($row['filename']));
$id = $row['id'];
echo "<tr>";
echo "<td>";
echo '<a href="';
echo $link;
echo '"><img src="thimg/';
echo $filename;
echo '" alt="';
echo $client;
echo '"></a>';
echo "</td>";
echo "</tr>";
}
}
Make the link point to a page which takes the ID of the ad as a parameter, something like click.php?id=the_id. Then that page can update the database, look up the link, and then you can use a header redirect to forward them on to the link. Make sure you don't output anything on that forwarding page though, or the redirect won't work.
This should get you what you need, without the need for javascript or ajax.

How could I show only selected row in PHP?

I'm working at this thing that takes information from a MySQL database that comes from a contact form and displays it all to the user. Well, I got that far without issues using:
$result = mysql_query("SELECT * FROM contact");
while($row = mysql_fetch_array($result))
{
echo $row['name'] . "<br/>" . " " . $row['email'] . "";
echo "<br/>";
echo $row['message'];
echo "<br />";
}
Now I would like to add a button next to each item that would single them out, basically taking me to a page where only the selected row shows up, not all of them, as happens on this page.
The thing is that i don't know how to do that. So, does anyone have any ideas?
Thanks!
Add a button that refreshes the page with a "GET" parameter, such as yourpage.php?uid=123; Then do
if ($_GET['uid'] !== null) {
$id = (int) $_GET['uid'];
$result = mysql_query('SELECT * FROM contact WHERE id='.$id);
...
}

Pagination Error

Im trying to do pages for my search result.My Search function is working fine. However, when I click on the page number. This error appears (below) :
Notice: Undefined index: search in C:\wamp\www\I-Document\new.php on line 8
ERROR: Select from dropdown
This message only should appear when there is no input in dropdown and no search input.
Im not sure how to correct this. Please help! Thank u
<?php
//connecting to the database
include 'config.php';
$search = mysql_escape_string($_POST['search']);
$dropdown = mysql_escape_string($_POST['dropdown']);
if (empty($search) && empty($dropdown)) {
die("Please choose your Search Criteria");
}
//max displayed per page
$per_page = 10;
//get start variable
$start = $_GET['start'];
//count records
$record_count = mysql_query("SELECT COUNT(*) FROM document WHERE $dropdown LIKE '%$search%'");
//count max pages
$max_pages = $record_count / $per_page;
if (!$start)
$start = 0;
//display data
$query = mysql_query("SELECT *
FROM document
WHERE $dropdown LIKE '%$search%'
LIMIT $start, $per_page");
echo "<b><center>Search Result</center></b><br>";
$num=mysql_num_rows($query);
if ($num==0)
echo "No results found";
else {
echo "$num results found!<p>";
}
echo "You searched for <b>$search</b><br /><br /><hr size='1'>";
echo "<table border='1' width='600'>
<th>File Reference No.</th>
<th>File Name</th>
<th>Owner</th>
<th>Borrow</th>
</tr>";
while ($rows = mysql_fetch_assoc($query)) {
echo "<tr>";
echo "<td>". $rows['file_ref'] ."</td>";
echo "<td>". $rows['file_name'] ."</td>";
echo "<td>". $rows['owner'] ."</td>";
echo "<td>Borrow</td>";
echo "</tr>";
}
echo "</table>";
//setup prev and next variables
$prev = $start - $per_page;
$next = $start + $per_page;
//show prev button
if (!($start<=0))
echo "<a href='new.php?start=$prev'>Prev</a> ";
//show page numbers
//set variable for first page
$i=1;
for ($x=0;$x<$record_count;$x=$x+$per_page) {
if ($start!=$x)
echo " <a href='new.php?start=$x'>$i</a> ";
else
echo " <a href='new.php?start=$x'><b>$i</b></a> ";
$i++;
}
}
//show next button
if (!($start>=$record_count-$per_page))
echo " <a href='new.php?start=$next'>Next</a>";
?>
Looks to me like when you click on a link, you no longer have the POST data being sent (it becomes a simple GET request). You'll need to create a form, then have a submit button for each of the pages. Or have the search term in the Query String, like Google (google.com/search?q=your+search+term+here)
This is the offending line
$search = mysql_escape_string($_POST['search']);
Your logic goes
IF $_POST['submit'] IS NOT SET
THEN
$search = mysql_escape_string($_POST['search']);
It's a pretty safe bet to say that if $_POST['submit'] is not set, then neither is $_POST['search']
Also, consider when you click one of your "page" links, that will issue a GET request and $_POST will be empty. You can either pass your POST parameters via GET along with the pagination data and look for them in either $_GET or $_POST (or $_REQUEST if you're feeling saucy), or create your pagination control as a "postable" form.
You already have all the code. You just need to rewrite your error condition.
Get the input variables
Encode them
Test for presence of both or die() with error message
So from your description:
$search = mysql_escape_string($_POST['search']);
$dropdown = mysql_escape_string($_POST['dropdown']);
if (empty($search) && empty($dropdown)) {
die("ERROR: whatever");
}
In this case you can test with empty() even after the escaping, because it would be an empty string in any case.
if (isset($_POST["search"])){
$search = mysql_escape_string($_POST['search']);
}else{
$search = mysql_escape_string($_GET['search']);
}
do the same for $_POST['dropdown']
but when printing out each page link , you should add the &search= and &dropdown= in the href of the page number .

Categories