How do i create pagination for my search results - php

I'm trying to create pagination for my search results. I'm able to create a working pagination if I drop the search functionality (i.e by not including if (isset($_POST['submit-search'])) and LIKE %search%) but once I include these, as seen in the code beneath, I only get a blank page when I click the next page, like as if the sql terms isn't kept in memory.
<?php
if (isset($_POST['submit-search'])) {
$results_per_page = 2;
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%' OR a_text LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
$number_of_pages = ceil($queryResult/$results_per_page);
// determine which page number visitor is currently on
if (!isset($_GET['page'])) {
$page = 1;
} else {
$page = $_GET['page'];
}
$this_page_first_result = ($page-1)*$results_per_page;
$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%' OR a_text LIKE '%$search%'LIMIT ".$this_page_first_result.",".$results_per_page." ";
$result = mysqli_query($conn, $sql);
// echoing the search results
while ($row = mysqli_fetch_assoc($result)) {
echo "<h3>".$row['title']."</h3>
<p>".$row['text']."</p>";
}
// echoing the pagination
for ($page=1;$page<=$number_of_pages;$page++) {
echo "<li><a href='search_results.php?page=".$page."'>".$page."</a></li>";
}
}
?>
html
<form action="search_results.php" method="POST">
<input type="text" name="search"placeholder="Search">
<button type="submit" name="submit-search">go</button>
</form>

The logic is wrong.
// this code is only executed on the initial search.
if (isset($_POST['submit-search'])) {
When the user go's to the next page:
echo "<li><a href='search_results.php?page=".$page."'>".$page."</a></li>";
Only a page number is given and the search parameter is lost as nothing is posted, so the first if statement will not run again.
You could do something like:
echo "<li><a href='search_results.php?page=".$page."&search=$search'>".$page."</a></li>";
And:
if(isset($_POST['submit-search']) || isset($_GET['search'])){
$search = ...;
}

Related

Passing php variables through pages / sql

i have the following information displayed
<?php
$my_query="SELECT * FROM games";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) > 0)
while ($myrow = mysqli_fetch_array($result))
{
$description = $myrow["game_description"];
$image = $myrow["gamepic"];
$game_id = $myrow["game_id"];
$gamename = $myrow["game_name"];
echo "<div class='cover'>
</div>";
}
?>
as you can see i have created a game_details page which will display that specific Game_id when the image is clicked
im having trouble understanding how to pull the data out from that game_id in sql on the other page.
here is my attempt on the game_details page
<?php
if (!isset($_GET['$game_id']) || empty($_GET['game_id']))
{
echo "Invalid category ID.";
exit();
}
$game_id = mysqli_real_escape_string($connection, $_GET['game_id']);
$sql1 = "SELECT * games WHERE game_id={$game_id}'";
$res4 = mysqli_query($connection, $sql1);
if(!$res4 || mysqli_num_rows($res4) <= 0)
{
while ($row = mysqli_fetch_assoc($res4))
{
$gameid = $row['$game_id'];
$title = $row['game_name'];
$descrip = $row['game_description'];
$genre = $row['genretype'];
echo "<p> {$title} </p>";
}
}
?>
This attempt is giving me the "invalid category ID" error
Would appreciate help
There are a few issues with your code.
Let's start from the top.
['$game_id'] you need to remove the dollar sign from it in $_GET['$game_id']
Then, $row['$game_id'] same thing; remove the dollar sign.
Then, game_id={$game_id}' will throw a syntax error.
In your first body of code; you should also use proper bracing for all your conditional statements.
This one has none if (mysqli_num_rows($result) > 0) and will cause potential havoc.
Rewrites:
<?php
$my_query="SELECT * FROM games";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) > 0){
while ($myrow = mysqli_fetch_array($result))
{
$description = $myrow["game_description"];
$image = $myrow["gamepic"];
$game_id = $myrow["game_id"];
$gamename = $myrow["game_name"];
echo "<div class='cover'>
</div>";
}
}
?>
Sidenote for WHERE game_id='{$game_id}' in below. If that doesn't work, remove the quotes from it.
WHERE game_id={$game_id}
2nd body:
<?php
if (!isset($_GET['game_id']) || empty($_GET['game_id']))
{
echo "Invalid category ID.";
exit();
}
$game_id = mysqli_real_escape_string($connection, $_GET['game_id']);
$sql1 = "SELECT * games WHERE game_id='{$game_id}'";
$res4 = mysqli_query($connection, $sql1);
if(!$res4 || mysqli_num_rows($res4) <= 0)
{
while ($row = mysqli_fetch_assoc($res4))
{
$gameid = $row['game_id'];
$title = $row['game_name'];
$descrip = $row['game_description'];
$genre = $row['genretype'];
echo "<p> {$title} </p>";
}
}
?>
Use error checking tools at your disposal during testing:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
You want to be using $_GET['gameid'] as that's the parameter you passed.
You are calling for game_id when the link to go to game_details.php has the variable gameid. Either change the parameter in the link to game_id or call for gameid in your $_GET['$game_id'].
Also, as Fred -ii- said, take out the dollar sign in $_GET['$game_id']

PHP MySQL if/while loop preventing creation of records. Relates to JQuery multiple image upload

I'm trying to get a multiple image upload to save the details of each image to a MySQL table record. One of the fields is 'pageNum', which I'm trying to determine automatically based on a check; if the currently checked page number (e.g. '1') is taken, it increments until it finds the next available one (e.g. 2 is taken but 3 isn't, so pageNum becomes '3').
Here is the PHP code for the upload section.
if(move_uploaded_file($image['tmp_name'], $upload_path.$image_name)){
include_once('includes/conn.inc.php');
$pageNum = 1;
$pageCheck = 0;
while($pageCheck == 0)
{
$query = ("SELECT pageNum FROM page WHERE comicID = '".$setComic."' AND pageNum = '".$pageNum."'");
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) = 0);
{
$id = 0;
$id_check = 0;
while($id_check == 0)
{
$query1 = ("SELECT pageID FROM page WHERE pageID = '".$id."'");
$result1 = mysqli_query($conn, $query1);
if (mysqli_num_rows($result1) > 0)
{
$id++;
}
else
{
mysqli_query($conn, "INSERT INTO page(pageID, pageNum, pageLocation, comicID) VALUES('".$id."', '".$pageNum."', '".$upload_path.$image_name."', '".$setComic."')");
$id_check++;
}
}
$pageCheck++;
}
else
{
$pageNum++;
}
}
mysqli_close($conn);
}
Currently, the code is not uploading any images at all. If I remove the while loop for $pageCheck and only use the following code, I'm able to upload images perfectly fine with full functionality, except for choosing what the page number is.
Working code (minus the pageNum feature):
if(move_uploaded_file($image['tmp_name'], $upload_path.$image_name)){
include_once('includes/conn.inc.php');
$id = 0;
$id_check = 0;
while($id_check == 0)
{
$query1 = ("SELECT pageID FROM page WHERE pageID = '".$id."'");
$result1 = mysqli_query($conn, $query1);
if (mysqli_num_rows($result1) > 0)
{
$id++;
}
else
{
mysqli_query($conn, "INSERT INTO page(pageID, pageNum, pageLocation, comicID) VALUES('".$id."', '".$pageNum."', '".$upload_path.$image_name."', '".$setComic."')");
$id_check++;
}
}
mysqli_close($conn);
}
echo '{"status":"error"}';
exit;
}
With this, the pageNum is always 0, but files upload with the correct IDs.
Including the relevant section of the HTML form just to be thorough.
<form id="upload" method="post" action="upload.php" enctype="multipart/form-data" >
<div id="drop">
Drop Here
<a>Browse</a>
<input type="file" name="upl" multiple />
</div>
<ul>
<!-- The file uploads will be shown here -->
</ul>
</form>
Thanks in advance.
Okay:
As sємsєм Find do use double equal for check ==
And single for store data
if (mysqli_num_rows($result) = 0);
Change with
if (mysqli_num_rows($result) == 0);
That said, an IF statement use the sintax:
IF(Condition){
//Code
}
You need to delete your semicolon on this line:
if (mysqli_num_rows($result) == 0);
(it will become)
if (mysqli_num_rows($result) == 0){//Code here}
Your problem in the first if inside the while loop:
if (mysqli_num_rows($result) = 0)
it should be something like
if (mysqli_num_rows($result) == 0)
or
if (mysqli_num_rows($result) === 0)

My PHP Search Function isn't Outputting Data

So I am trying to create a way of searching my website. I've created a search bar on my index page. You can find this page here: http://seersvillage.com/v1.2/
My search form looks like this:
<form method="post" action="search.php">
<input type="text" name="search" class="search" value="Skeleton" onFocus="this.value=''">
</form>
and I have a functions.php file attatched and this page is also connected to my mysql database. I have content available to be read / searched for all ready.
Here is my search function on functions.php:
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM entries WHERE name LIKE '%$searchq%' or description LIKE '%$searchq%' or content LIKE '%$searchq%'") or die("Could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'there was no search results!';
} else {
while($row = mysql_fetch_array($query)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$output .= '<div>'.$eName.' '.$eDesc.'</div>';
}
}
}
}
And the only thing on my search.php (excluding your usual html layout) is as follows:
<?php
include('includes/functions.php');
if(!isset($_POST['search'])) {
header("Location:index.php");
}
?>
and further down in the tags.
<?php print("$output");?>
Now I am pretty new to PHP and MySQL. However I am getting no error on my error.log file, making troubleshooting a little hard for a first timer. Any suggestions? I'm sure it's a very simple mistake, probably just misspelt something, but I just can't see it.
it seems that your php.ini file is set to not display errors. Add these lines of code at the beginning of your code and retry:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
Your doSearch function does not return anything.
return $output;
But $output is only declared within the function. So you'll need to use
print(doSearch());
Either that or declare $output as a global variable, but we don't want to do that :)
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM entries WHERE name LIKE '%$searchq%' or description LIKE '%$searchq%' or content LIKE '%$searchq%'") or die("Could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'there was no search results!';
} else {
while($row = mysql_fetch_array($query)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$output .= '<div>'.$eName.' '.$eDesc.'</div>';
}
}
//make sure your function returns $output
return $output;
}
Make sure your function returns the output and then echo out the function:
<?php echo doSearch(); ?>
This is because of how PHP variables are scoped.
...then of course we need to add in all the standard provisos ... don't use the mysql_ library it's almost as dead as a Norwegian Blue. If you use mysqli or PDO you can bind the parameters/values to a prepared statement and not only will that improve efficiency but it'll ensure your input is properly sanitised (far better than that odd ad-hoc preg_replace you're using).
You don't want to kill your script (die) when the query fails - that's just a bit weird, handle the error properly.
There are far better ways to do searches in SQL such as FULLTEXT searches.. or if you can, perhaps implement Apache Solr rather than trying to roll your own.

PHP Show next image in the table

I am showing an image on my page from the db table like this:
<?php
if ($db_found) {
$SQL = "SELECT * FROM myTable where id='$posted_id'";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
echo '<img src="images/'.$db_field['image'].'" alt="" />';
}
mysql_close($db_handle);
}
?>
Next
How can I do so that if $posted_id is for example 1 ... when I click the "Next" link the image id = 2 appears and so on.
for that you need to either refresh page or use ajax.
you can pass variable posted_id in url like this.
Next
this way you can pass next id from database .. if your id falls in sequence.
you also need to programatically handle issue like what to do if record of next id does't exist in database..
You should work with the MySQL LIMIT and ORDER filters.
<?php
if (isset($_GET['current'])) {
$current = $_GET['current'];
} else {
$current = 0;
}
$request = "SELECT * FROM myTable ORDER BY id ASC LIMIT " . $current . ",1";
?>
And then, just to catch the next item, you can do something like that:
<?php
// make the last item point to the first one
$loop = true;
$count = "SELECT COUNT(*) FROM myTable";
if ($current < $count) {
$next = $current + 1;
} else if ($loop) {
$next = 0;
// no loop, then just stay at the end
} else {
$next = $current;
}
?>

show page in words in address bar

I need a little help of my brilliant friends.
Actually i m new to development so that i have no much idea how can i show my page in words like www.testsite.com/index.php?pname=**Home** except of www.testsite.com/index.php?pid=**1**
i have the following code for showing page in number
if (!$_GET['pid']) {
$pid = '1';
} else {
$pid = ereg_replace("[^0-9]", "", $_GET['pid']); }
and the sql code
$sqlCommand = "SELECT id, link FROM main_page WHERE showing='1' ORDER BY id ASC";
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
$menu='';
while ($row = mysqli_fetch_array($query)) {
$pid = $row["id"];
$link = $row["link"];
if ($linklabel){
$menu .=''. $link .'';
}}
i want to show and href name of page not id how can i do that.
help plz
Your example will fail if I enter *1*2*3*
you should be searching for the contents of
**(contents)**
and nothing else.
That will get you the name and the number.
Here is my example
$string = "**123naasdme456**";
preg_match("/[^\*+](?P<val>\w+)[^\*+]/",$string,$matches);
echo $matches[0];
will echo 123naasdme456
and here it is implemented into your code
function getReal($urlVar)
{
if(preg_match("/[^\*+](?P<val>\w+)[^\*+]/",$urlVar,$matches))
{
return $matches[0];
}
return false; // or default value
}
$pid = getReal($_GET['pid']);
$name = getReal($_GET['pname']);
You should add an extra field in your database (table main_page) with the name name or something similar. Then you could:
if (!$_GET['pname']) {
$pid = 'home';
} else {
$pid = mysql_real_escape_string($pid);
$sql = mysql_query("SELECT name FROM main_page WHERE name = '$pid'");
if (mysql_num_rows($sql) == 1))
{
echo "Content";
} else {
echo "404 error. Couldn't find the page you were looking for.";
}
}
URL Rewriting. http://www.addedbytes.com/for-beginners/url-rewriting-for-beginners/

Categories