PHP Combining search function with pagination - php

So I'm trying to make a page where i can display results from my database table. You should be able to search and there should be some pagination as there are thousands of results.
I've managed to make a page which just has the search, and works perfect. So now i need to know how would would integrate some pagination into that.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="container">
<form action="" method="get">
<input type="text" name="search" id="search" placeholder="Search" />
<input type="submit" />
</form>
<?php include 'process.php'; ?>
</div> <!-- /container -->
<script src="js/jquery.js"></script>
<script src="js/script.js"></script>
</body>
</html>
process.php
<?php include 'dbconfig.php'; ?>
<?php include 'connect.php'; ?>
<?php
$search = $_GET['search'];
$result = mysql_query("SELECT * FROM oantkb WHERE Name LIKE '%$search%' ORDER BY `INDEX` DESC");
echo '<table class="table">';
echo '<thead>';
echo '<tr>';
echo '<th>#</th>';
echo '<th>Pic</th>';
echo '<th>Name</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while($row = mysql_fetch_assoc($result)) {
$pic = $row['Pic'];
$name = $row['Name'];
echo '<tr>';
echo '<td>#</td>';
echo '<td><img src="'.$pic.'" height="50" width 50"></td>';
echo '<td>'.$name.'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
?>
Right now it works like it should. When i search it will say index.php?search=banana, but i need some pagination added so it will say for example index.php?search=banana&?page=2. Or something along those lines. Hope it makes sense...i'm a php newb :)

Include at the end of your sql query the following:
$resultsPerPage=10;
$page = ($_GET["page"]-1)*$resultsPerPage;
$query = $query." LIMIT $page,$resultsPerPage";
mysql_query($query);
By the way the mysql_ library is deprecated in favor of mysqli.
Also the above is susceptible to sql injection attacks because $_GET["page"] isn't first sanitized, but for simplicity I did it this way.
This assumes a paging scheme that starts at 1.

i've been using Pear Pagination for a long time. you can try it.
here is a good tutorial for setting it up
Simple Pagination in PHP tutorial
a good thing to add is clean your variable before using them in your query.

Related

Loading a PHP page into a HTML div

So I am currently trying to create a portion of my website that fetches a mySQL table. I wrote the php to fetch the data, create a table, and print out the table in a separate php file named display.php. Now i am trying to load it into a div on my html page but for some reason it is not working. I am using XAMPP and php is working as my login page works. Here is the code:
HTML: (I have tried both include and require)
<html>
<body>
<div id="display" class="myCustom1">
<?php require('display.php'); ?>
</div>
<div id="display" class="myCustom1">
<?php include("display.php"); ?>
</div>
</body>
</html>
PHP: (if i run just the php page it creates the table)
<?php
$servername = "localhost";
$username = "test";
$password = "test";
$database = "data1";
//create connection & access DB
$connect = mysqli_connect("$servername","$username","$password","$database");
//if error, display error
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($connect,"SELECT * FROM data1enter");
echo
"
<table border='1'>
<tr>
<th>Song</th>
<th>Author</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['song'] . "</td>";
echo "<td>" . $row['author'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($connect);
?>
You are using <?php ?> tags in the html file, Change the extension of the file containing the below code to .php from .html and you will be able to use include function.
<html>
<body>
<div id="display" class="myCustom1">
<?php require('display.php'); ?>
</div>
<div id="display" class="myCustom1">
<?php include("display.php"); ?>
</div>
</body>
</html>
Also make sure the include path is correct.
Hope it helps !
Display should be blade template ..
#include('display')
Give path to display template
Just put the php in a function. Then you can do this:
<html>
<body>
<?php require_once('display.php'); ?>
<div id="display" class="myCustom1">
<?php render(); ?>
</div>
</body>
</html>
<?php
function render()
{
//YOUR PHP CODE
}
?>

PHP - echo doesn't seem to work right

I have this function that gets a table from another site by finding each row of that table and, providing that row isn't a duplicate, echos it to my site. I want to add my own row to the bottom though so I thought it would be as simple as just echoing
<tr><td>TEXT</td></tr>
as you can see below. But when I load the page, this row isn't added. Anyone know what the cause may be?
Here is the website if that helps.
function getStats(){
$page = file_get_html(getPageURL());
$rows = array();
echo "<table id=statsTable>";
foreach($page->find('html/body/div/div[1]/center/table/tbody/tr[1]/td/table/tbody/tr/td[2]/table/tbody/tr/') as $key=>$element) {
if(!in_array($element, $rows)){
$rows[$key]=$element;
echo $rows[$key-1];
}
}
echo "<tr><td>Viewing old updates will be added soon</td></tr></table>";
}
Main problem was in key offset, when you work with arrays it's better to use keys in this case. So in order to that I've changed the in_array to array_key_exists, because we want to check if key exists, but if you want to work with element you have to know its key.
function getStats(){
$page = file_get_html(getPageURL());
$rows = array();
echo "<table id=statsTable>";
foreach($page->find('html/body/div/div[1]/center/table/tbody/tr[1]/td/table/tbody/tr/td[2]/table/tbody/tr/') as $key => $element) {
if(!array_key_exists($key, $rows)){
$rows[$key] = $element;
/* Echo only when it exists */
if(array_key_exists($key-1, $rows)){
echo $rows[$key-1];
}
}
}
echo "<tr><td>Viewing old updates will be added soon</td></tr></table>";
}
?>
<?php
include "getData.php";
include "simple_html_dom.php";
?>
<!DOCTYPE HTML>
<html>
<head>
<title>KSA Flight Tracker</title>
<link rel="stylesheet" type="text/css" href="KSAStyle.css"/>
</head>
<body>
<div id="page">
<div id="leftPanel">
<p id="missionsHeader">Active Missions</p>
<?php getList(); ?>
</div>
<div id="mainPanel">
<p id="infoHeader">
<?php getTitle(); ?>
</p>
<div id="info">
<center>
<?php
getInfo();
getImage();
getMap();
getStats();
?>
</center>
</div>
</div>
</div>
</body>
</html>

Linking to search results directly

I got myself into a project at work that is going beyond my (very modest) coding skills.
So i have a database with 6 fields. I'm able to make searchs on it using php (i followed a youtube tutorial), add records, delete records and update records. All of that is working just fine.
What i need now is this:
I need to link search results (only a few, the most popular) on a image.
Per example, i have a company logo on my main page (let's say company name is..i dunno.. "Google". When i click on it, i wanted it to redirect to the search results of "google", like if i had inserted that in the search field. Is that possible?
(notice that i don't have companies in my database, i'm just trying to give an example so that people can understand what i intend. In my database i would need to link to reflect search results of the field "unidade")
Here is my code so far. The add / update .php i don't think are needed.
<?php
// include the connection file
include "connection.php";
$sql = "SELECT * FROM usuariotb";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .=" WHERE nome LIKE '%".$search_term."%'";
$sql .=" OR posto = '{$search_term}' ";
$sql .=" OR nim = '{$search_term}' ";
$sql .=" OR unidade LIKE '%".$search_term."%'";
$sql .=" OR codigoueo LIKE '%".$search_term."%'";
}
$query = mysql_query($sql) or die (mysql_error());
if (isset($_GET['recordId'])) {
$id = mysql_real_escape_string($_GET['recordId']);
$sql_delete = "DELETE FROM usuariotb WHERE id = {$id}";
mysql_query($sql_delete) or die(mysql_error());
header("location:display_data.php");
exit();
}
?>
<html>
<head>
<meta charset="iso-8859-1">
<title></title>
<link rel="stylesheet" type="text/css" href="format.css" />
</head>
<body>
<div class="container">
<form name="search_form" method="POST" action="display_data.php">
Search: <input type="text" name="search_box" value=""/>
<input type="submit" name="search" value="Procurar">
</form>
<div class="container">
<div class="content">
<div class="toolbar">Adicionar Novo Militar</div>
</div>
<div class="toolbar">Voltar à página de pesquisa</div>
</div>
</div>
<div class="container">
<div class="content">
<table width="90%" cellpadding="5" cellspacing="5">
<tr>
<td><strong>Nome</strong></td>
<td><strong>Nim</strong></td>
<td><strong>Posto</strong></td>
<td><strong>Unidade</strong></td>
<td><strong>Sigla Unidade</strong></td>
<td><strong>Observações</strong></td>
<td><strong>Acções</strong></td>
</tr>
<?php if (mysql_num_rows($query)) { ?>
<?php while ($row=mysql_fetch_array($query)) {?>
<tr>
<td><?php echo $row['nome'];?></td>
<td><?php echo $row['nim'];?></td>
<td><?php echo $row['posto'];?></td>
<td><?php echo $row['unidade'];?></td>
<td><?php echo $row['codigoueo'];?></td>
<td><?php echo $row['observacoes'];?></td>
<td>Delete</td>
<td>Edit</td>
</tr>
<?php } /* end loop */ ?>
<?php } else { ?>
<h2> Nothing to display!</h2>
<?php } /* end rows checking */ ?>
</table>
</div>
</div>
</body>
</html>
First of all, I empathize with you regarding being tasked with a more complex task than your current ability. Been there, done that. Many companies do this.
Regarding your task, for search every website usually uses GET to do the search e.g. https://www.google.co.in/search?q=stackoverflow. Notice the q=stackoverflow part. For this you do not need to submit any form, just use the URL directly.
So, I suggest you visit the websites where you want to link directly for search. Search for some sample text, say TEST and observe the URL of the page that opens.
Then using JavaScript/jQuery/etc, on click of the logo, read whatever text you want to search, create a URL in JavaScript and redirect there.
This is the general idea, feel free to comment and ask if you face any issues in implementation.

Delete PDO OOP Problems

Good day everyone.
I totally need your help.I am pretty new to oop & pdo and I am having problems with my delete function. The item will not be delete whenever I click the delete button. It seems like I can't call the id. I just don't know what to do. Please help me solve this problem.
Here is my code.
For the class(codex):
public function deleteData($id,$table)
{
$q = "DELETE FROM $table WHERE id = :id";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':id'=>$id));
}
For the UI and the page where I call the id:
<?php
include_once "../styles/header-menu-out.php";
include_once "dbconnection.php";
function __autoload($class){
include_once("../main/".$class.".php");}
$code = new codex("localhost","library_books","root","" );
$books = $code->showData("book_info");
if(isset($_REQUEST['id'])){
if($code->deleteData($_REQUEST['id'],"book_info")){
echo "<script type='text/javascript'>
alert('Book Information have been deleted.');
window.location='bookDeleteUI.php';
</script>";
}}
?>
<html>
<head><link rel="stylesheet" type="text/css" href="../styles/library_style.css"></head>
<title>Book-A-Holic: Delete & Update Books</title>
<body><br /><center>
<div id="content"><div class="echoname"><br/><br/><b><h2>Book Settings</h2></b><br/></div>
<table id="tablecolor" class="echoname" border="1">
<td>ID</td>
<td>Title</td>
<td>Author</td>
<td>ISBN</td>
<td>Publisher</td>
<td>Language</td>
<td>Genre</td>
<td>Quantity</td>
<td>Availability</td>
<td>Queue</td>
<td><center>Settings</center></td>
<?php
echo "<pre>";
foreach ($books as $book)
{
echo "<tr>";
extract($book);
echo "<td>".$id."</td>";
echo "<td>".$title."</td>";
echo "<td>".$author."</td>";
echo "<td>".$isbn."</td>";
echo "<td>".$publisher."</td>";
echo "<td>".$language."</td>";
echo "<td>".$genre."</td>";
echo "<td>".$quantity."</td>";
echo "<td>".$availability."</td>";
echo "<td>".$queue."</td>";
?>
<td><button class="btn"><a href="bookUpdateUI.php?update=$id" >Edit</a></button>
<button class="btn">Delete</button></td>
<?php echo "</td>";
}
echo "</pre>";
?>
</table><br />
</div></center>
</body>
</hmtl>
<?php include_once "../styles/footer-admin.php"; ?>
Looks like you've almost got it and well done on using PDO with parametized queries. The problem is that you're not outputting the $id through the php interpreter. You need to do this:
<button class="btn">Delete</button></td>

If i choose an option in the selectbox it be must fill a other textbox

If i choose a meal than come the price not in the textbox.
What i want is that if i choose an option in the selectbox that the texbox automatic fills with the price.
<!DOCTYPE html>
<?php
include ("connection.php");
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<meta charset="utf-8">
<title>Kantine</title>
</head>
<body>
<div id="container">
<div id="logo"></div>
<div id="header">
<h1> Change or Delete meals</h1>
</div>
<div id="menu"></div>
<div id="content">
<?php
echo '<select name="Meals">';
$result = mysqli_query($con,"SELECT meal, price FROM meals") ;
while($row = $result->fetch_assoc())
{
echo "<option value=\""."\">" . $row['meal']."</option>\n";
echo "<br />";
}
echo '</select>';
echo '<input type="text" value="' . $row['price'] . '"/>';
mysqli_close($con);
?>
</div>
<div id="footer"></div>
</div>
</body>
</html>
PHP is not suitable for client side scripting. What you want depend on the user choice on the browser side, therefore you'll need Javascript for that. If that action requires a database connection then you may want to use AJAX to connect to a PHP script and get the query results.
Take a look at the jQuery framework and specifically to the ajax section of it.
Have you tried escaping the " in your first echo? Also some of your html can be moved out of the php section, and you dont need linebreaks between option elements. And mixing single and double quotes is a sure way to get into trouble. Be consistent.
<select name="Meals">
<?php
$result = mysqli_query($con,"SELECT meal, price FROM meals") ;
while($row = $result->fetch_assoc())
{
echo "<option value=\"". $row['meal'] . "\">" . $row['meal'] . "</option>";
}
echo "<input type=\"text\" value=\"" . $row['price'] . "\"/>";
mysqli_close($con);
?>
</select>

Categories