I'm a PHP student and I'm developing my first app. I need to add pagination on the search results with this code below. I can't use datatables or another plug-ins because it's hard for me to put action buttons and my data on table.
If you know some simple method that can be not so hard to implement will help a lot.
I'm using the example from this dev: how to search and filter with php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `users` WHERE CONCAT(`id`, `fname`, `lname`, `age`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `users`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="php_html_table_data_filter.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['fname'];?></td>
<td><?php echo $row['lname'];?></td>
<td><?php echo $row['age'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
Below example will work wells for requirements :
mysql_connect("localhost","wellho","wawawawa");
mysql_select_db("wellho");
$perpage = 10;
$html = "";
$startat = $_REQUEST[page] * $perpage;
$limlim = "%".$_REQUEST[look4]."%";
$q = mysql_query("select count(entry_id) from mt_entry where entry_title like '$limlim'");
$row = mysql_fetch_array($q);
$havesome = $row[0];
$pages = floor(($row[0]-1) / $perpage) +1 ;
$q = mysql_query("select * from mt_entry where entry_title like '$limlim' order by entry_id desc limit $startat,$perpage");
while ($row = mysql_fetch_assoc($q)) {
$text = strip_tags($row[entry_text]);
$text = substr($text,0,300);
$html .= "<dt>$row[entry_id] - <a href=/mouth/$row[entry_id]_.html target=pix>$row[entry_title]</a></dt>";
$html .= "<dd>$text ....<br><br></dd>";
};
$lynx = "Please choose the next page you want to view:";
for ($k=0; $k<$pages; $k++) {
if ($k != $_REQUEST[page]) {
$lynx .= " ".($k+1)."";
} else {
$lynx .= " <b>--".($k+1)."--</b>";
}
}
if ($pages < 2) {
$lynx = "All results shown on this page";
}
if ($havesome == 0) {
$lynx = "Sorry - no titles matched. Please change your search string";
}
?>
<html><head>
<title>Showing blog entries</title>
<body>
<h2>Search titles on "The Horse's Mouth"</h2>
<form>Search only for titles including ... <input name=look4
value="<?= htmlspecialchars(stripslashes($_REQUEST[look4])) ?>">
(Please leave box empty to select all titles)<br>
<input type=submit></form><br>
<h2>Here are the entries you selected - page <?= $_REQUEST[page]+1 ?>:</h2><br>
<?= $html ?>
<?= $lynx ?>
</body>
You should use limit and offset to paginate the results.
<?php
...
// If no 'page' parameter is found, default to 1
$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
// Results per page
$limit = 10;
// Offset = (page - 1) * limit. (page 1 = 0, page 2 = 10, etc...)
$offset = ($currentPage - 1) * $limit;
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `users` WHERE CONCAT(`id`, `fname`, `lname`, `age`) LIKE '%".$valueToSearch."%' LIMIT $limit OFFSET $offset";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `users` LIMIT $limit OFFSET $offset";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="php_html_table_data_filter.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['fname'];?></td>
<td><?php echo $row['lname'];?></td>
<td><?php echo $row['age'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
Previous
Next
</body>
</html>
PS: In the previous example i didn't checked if the page is the first or last, you should do that.
Related
I'm having trouble getting my php search project working properly, having followed a guide, I don't fully understand the guide/code. My search bar will allow me to search for jobs in the database, but currently it shows all jobs and filters the one you search.
Is it possible to display these jobs as links, where it will take you to another page and display the currently selected job.
Here is my current code:
<?php
require 'config.php';
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `job` WHERE CONCAT(`location`, `description`, `budget`, `duedate`,`title`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `job`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$conn = mysqli_connect("localhost", "root", "", "bid4myjob");
$filter_Result = mysqli_query($conn, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="php_html_table_data_filter.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="submit" value="Search"><br><br>
<table>
<tr>
<th>Title</th>
<th>Location</th>
<th>Description</th>
<th>Budget</th>
<th>Due date</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['title'];?></td>
<td><?php echo $row['location'];?></td>
<td><?php echo $row['description'];?></td>
<td><?php echo $row['budget'];?></td>
<td><?php echo $row['duedate'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
Your problem is this line:
if(isset($_POST['search']))
There's no variable called "search" which will be submitted by your form, so its value will never be set, and this if block will never be entered. I suspect you've confused the "name" attribute which determines the variable's name in the POST array, with its value ("Search", in the case of your button). Try
if(isset($_POST['submit']))
instead.
See also my comments above about your security problems and aim to fix those a.s.a.p.
Could someone please help me how to do this?
When I click a link, it will be directed to a new page containing the contents related to the value of the link. Like for example, after clicking the title of an article, it will be directed to a new page containing its content. So the value of the link will be used in search.
search.php
<?php
if(isset ($_POST['valueTosearch']))
{
$valueToSearch = $_POST['valueToSearch'];
$query = "SELECT * FROM `events` WHERE CONCAT(`title`) LIKE
'%".$valueToSearch ."%'";
$search_result = filterTable($query);
}
else {
$query="SELECT * FROM `events`";
$search_result = filterTable($query);
}
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "silangagri");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black ;
}
</style>
</head>
<body>
<table style="padding-right: 2; padding-left: 2; padding-top: 4; padding-
bottom: :4">
<tr>
<th>title</th>
<th>location</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)): ?>
<tr>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['location']; ?></td>
</tr>
<?php endwhile;?>
</table>
</body>
</html>
index.php
<?php
$host = "localhost";
$username="root";
$password="";
$database="silangagri";
$connect = new
PDO("mysql:host=$host;dbname=$database",$username,$password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM news ORDER BY date DESC";
$data = $connect->query($query);
?>
<!DOCTYPE html>
<html>
<body>
<form action = "search.php" method="post">
<?php foreach($data as $row) {
echo '<a name="valueTosearch" href="search.php">
<h5>'.$row["title"].'</h5></a>';
echo '<br><br>';?>
<?php
}
?>
</form>
</body>
</html>
I have a sample code for my problem. what i want to do is if i search for "Helloworld" then i want to inform the user that there's no data matched based from their inputted data. Im thinking if can i use if else statement to do a validation if the data inputted didn't matched any rows and if the inputted data matched some rows. As i visualized the solution for this problem i think this method is the solution but i don't how can i do this. i think the solution is to put if else condition here's my code how i thought about it
if the result of search is not nothing then it will show the result then if nothing then the message will appear "no data matched"
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `users` WHERE CONCAT(`id`, `fname`, `lname`, `age`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `users`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="php_html_table_data_filter.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<?php
if($result_validation != ''){
?>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['fname'];?></td>
<td><?php echo $row['lname'];?></td>
<td><?php echo $row['age'];?></td>
</tr>
<?php endwhile;?>
</table>
<?php
}else{
echo "no data matched";
}
?>
</form>
</body>
</html>
I see no point in displaying the entire table inside the form, you should display it somewhere outside of the form. Having said that, $result_validation variable is undefined, you need to use $search_result in your code.
And as per your question, use mysqli_result::$num_rows to check number of rows returned from the SELECT query.
if($search_result->num_rows){
// display table
}else{
echo 'no data matched';
}
hello kind sirs can you help me with this code. What i try to do is when i type something in the search box, ex. pending it will show the 5 pending reservation per page(5 rows of pending reservation). but when i try it, it shows all the pending reservation which is more than 10.
here is the image
i try something like this.. but it shows nothing
$query = "SELECT * FROM reservations WHERE CONCAT(firstname, lastname, reservationstatus)LIKE '%".$valueToSearch."%' LIMIT " . $this_page_first_result . ',' . $results_per_page";
Here is the whole code
<?php
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ERROR | E_PARSE);
session_start();
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "srdatabase";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$results_per_page = 5;
$select= "SELECT * FROM reservations";
$result = mysqli_query($conn, $select);
$number_of_results = mysqli_num_rows($result);
if(!isset($_GET['page']))
{
$page = 1;
}
else
{
$page = $_GET['page'];
}
$this_page_first_result = ($page-1)*$results_per_page;
$sql = "SELECT * FROM reservations LIMIT " . $this_page_first_result . ',' . $results_per_page;
$result = mysqli_query($conn, $sql);
$number_of_pages = ceil($number_of_results/$results_per_page);
?>
<div id="paging-div">
<?php
for($page=1;$page<=$number_of_pages;$page++)
{
echo '<a id="pagingLink" href="adminControl.php?page=' . $page . '">' . $page . '</a>';
}
?>
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
$query = "SELECT * FROM reservations WHERE CONCAT(firstname, lastname, reservationstatus)LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else
{
$query = "SELECT * FROM reservations";
$search_result = filterTable($query);
}
function filterTable($query)
{
$conn = mysqli_connect("localhost", "root", "", "srdatabase");
$filter_Result = mysqli_query($conn, $query);
return $filter_Result;
}
?>
</div>
<!DOCTYPE html>
<html>
<head>
<title>Admin Control</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="topnav" id="myTopnav">
Home
Speakers
About
Contact
Reservation
Sign Out
<?php echo $_SESSION['firstname']; ?>
Sign Up
Sign In
Admin control
☰
</div>
<br>
<br>
<br>
<br>
<h4 style="padding-left:10px; text-align:center;">Reservation List</h4>
<hr>
<form action="adminControl.php" method="POST">
<input type="text" name="valueToSearch" placeholder="type a value">
<input type="submit" name="search" value="Filter">
</form>
<br>
<br>
<div style="overflow-x:auto;">
<table class="reservations-table">
<tr>
<th class="thFirstName">First Name</th>
<th class="thLastName">Last Name</th>
<th class="thEmailAddress">Email Address</th>
<th class="thContactNumber">Contact Number</th>
<th class="thSpeaker">Speaker</th>
<th class="thTopic">Topic</th>
<th class="thLocation">Location</th>
<th class="thAudience">Audience</th>
<th class="thCount">Count</th>
<th class="thTime">Time</th>
<th class="thDate">Date</th>
<th class="thAction">Reservation Date</th>
<th class="thAction">Status</th>
<th class="thAction">Action</th>
<th class="thAction">Action</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['firstname'];?></td>
<td><?php echo $row['lastname'];?></td>
<td><?php echo $row['emailaddress'];?></td>
<td><?php echo $row['contactnumber'];?></td>
<td><?php echo $row['speaker'];?></td>
<td><?php echo $row['topic'];?></td>
<td><?php echo $row['location'];?></td>
<td><?php echo $row['audience'];?></td>
<td><?php echo $row['count'];?></td>
<td><?php echo $row['time'];?></td>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['reservationdate'];?></td>
<td><?php echo $row['reservationstatus'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</div>
<?php
$epr='';
$msg='';
if(isset($_GET['epr']))
$epr=$_GET['epr'];
if($epr=='delete')
{
$id=$_GET['id'];
$delete=mysqli_query($conn, "DELETE FROM reservations WHERE id=$id");
if($delete)
header('location:adminControl.php');
else
$msg='Error :'.mysqli_error();
}
?>
<?php
$epr='';
$msg='';
if(isset($_GET['epr']))
$epr=$_GET['epr'];
if($epr=='approve')
{
$id=$_GET['id'];
$approve=mysqli_query($conn, "UPDATE reservations SET reservationstatus='approved' WHERE id=$id");
header('location:adminControl.php');
}
?>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<script>
function ifAdmin()
{
document.getElementById("signIn").style.display = "none";
document.getElementById("signUp").style.display = "none";
document.getElementById("signOut").style.display = "block";
document.getElementById("adminControl").style.display = "block";
}
</script>
<script>
function ifNotAdmin()
{
document.getElementById("signIn").style.display = "none";
document.getElementById("signUp").style.display = "none";
document.getElementById("signOut").style.display = "block";
document.getElementById("adminControl").style.display = "none";
}
</script>
<script>
function ifNotLogin()
{
document.getElementById("user").style.display = "none";
document.getElementById("signOut").style.display = "none";
document.getElementById("adminControl").style.display = "none";
}
</script>
<?php
if (isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == true)
//if login
{
if($_SESSION['type'] == 1)
{
echo "<script type='text/javascript'>ifAdmin();</script>";
}
elseif($_SESSION['type'] == 0)
{
echo "<script type='text/javascript'>ifNotAdmin();</script>";
}
}
//if not login
else
{
echo "<script type='text/javascript'>ifNotLogin();</script>";
}
?>
<div id="footer" class="push">Copyright 2017</div>
</body>
</html>
... when i try it, it shows all the pending reservation which is more than 10.
That's because when you hit 2nd, 3rd, ... pages(after navigating from the 1st page), the $_POST array would be empty i.e. $_POST['search'] won't be set, and that's why else{...} part of the code will get executed every time you navigate to 2nd, 3rd, ... pages. Since you're not sending any sensitive data with the form, use GET instead of POST in the method attribute of the form, like this:
<form action="..." method="get">
and get the user inputted data like this:
if (isset($_GET['search'])) {
$valueToSearch = $_GET['valueToSearch'];
...
Subsequently, you need to attach that search query in each of your pagination links, so that the search query would be available when you hop from page to page.
// your code
<?php
for($page=1;$page<=$number_of_pages;$page++)
{
echo "<a id='pagingLink' href='adminControl.php?page=" . $page . "&valueToSearch=". urlencode($_GET['valueToSearch']) ."&search'>" . $page . "</a>";
}
?>
// your code
<html>
<body>
<center>
<div>
<form method="post" action="admission_list_fetch5.php">
Enter Cousre Code: <input name="course_code" placeholder="course code">
<input type="submit" name="submit" value="Submit">
</form>
<div>
<table border="2" id="enquirytable" style= "border-collapse:collapse;"">
<thead>
<tr>
<th style="width:50;">SL No</th>
<th>Student ID</th>
<th>Enrol No</th>
<th>Name</th>
<th>Course</th>
<th>Semester</th>
</tr>
</thead>
<tbody>
<?php
//error_reporting(0);
$num_rec_per_page=10;
mysql_connect('localhost','root','');
mysql_select_db('nobledatabase');
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
$course_code=$_POST['course_code'];
$sql = "SELECT * FROM admission_list where course_code='$course_code' LIMIT $start_from, $num_rec_per_page";
$rs_result = mysql_query ($sql); //run the query
$i=1;
while( $row = mysql_fetch_assoc( $rs_result ) )
{
echo ("<tr><td style='text-align:center'>$i</td>".
"<td>{$row['student_id']}</td>".
"<td>{$row['enrol']}</td>".
"<td>{$row['name']}</td>".
"<td>{$row['course']}</td>".
"<td>{$row['sem_year']}</td></tr>\n");
$i++;
}
?>
</tbody>
</table>
<?php
$sql="SELECT * FROM admission_list where course_code='$course_code'";
$rs_result = mysql_query($sql); //run the query
$total_records = mysql_num_rows($rs_result); //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
?>
</div><!--enquirytable-->
<div class="enquirypages">
<br>
<?php
echo "<a href='admission_list_fetch5.php?page=1&course_code=$course_code'>".'<<'."</a> "; // Goto 1st page
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='admission_list_fetch5.php?page=".$i."&course_code=$course_code'> ".$i." ";
};
echo "<a href='admission_list_fetch5.php?page=$total_pages&course_code=$course_code'>".'>>'."</a> "; // Goto last page
?>
</div>
</div>
</center>
</body>
</html>
Even if I pass the parameters to all the pages, I am getting the same error message:
Notice: Undefined index: course_code in C:\wamp\www\admission_list_fetch5.php on line 33
When I look at the logic it seems that the only value that supplies the course_code variable comes from the $_POST['course_code']. This means that you have to submit from a form post every time to populate this variable.
The assumption is that the 2nd code peace is the admission_list_fetch5.php.
Whenever paging occurs then clicking on the <a href link passing query strings at no point does course_code get assigned using a $_GET['course_code']. Therefore course_code query string will always be empty.
I would suggest the following on the assumption admission_list_fetch5.php
if(isset($_POST['course_code']))
{
$course_code = $_POST['course_code'];
}
if(isset($_GET['course_code']))
{
$course_code = $_GET['course_code'];
}
Not very elegant but serves the purpose. When you post to this page there should be not query string therefore the code will default to the $_POST['course_code']. If a query string was set for then it will override using $_GET['course_code'].