MySQL Query pagination with PHP - php

How can i add a pagination system to this simple item display? And how i can add pagination for the results from filter? I just get lost that part and i cant figure it out!
I want to apply CSS on the menu too!
Here's the code:
<?php
include('db.php');
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
$result = mysql_query("SELECT * FROM products where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
else
{
$result = mysql_query("SELECT * FROM products");
}
while($row=mysql_fetch_assoc($result))
{
echo '<li class="portfolio-item2" data-id="id-0" data-type="cat-item-4">';
echo '<div>
<span class="image-block">
<a class="example-image-link" href="reservation/img/products/'.$row['imgUrl'].'" data-lightbox="example-set" title="'.$row['Product'].'""><img width="225" height="140" src="reservation/img/products/'.$row['imgUrl'].'" alt="'.$row['Product'].'" title="'.$row['Product'].'" />
</a>
</span>
<div class="home-portfolio-text">
<h2 class="post-title-portfolio"><font color="#666666">'.$row['Product'].'</font></h2>
<p class="post-subtitle-portfolio"><font color="#666666">Descrição: '.$row['Description'].'
<p class="post-subtitle-portfolio"><font color="#666666">Categoria: '.$row['Category'].'
<p class="post-subtitle-portfolio">Código: '.$row['Price'].'</p><br/></font></p>
</div>
</div>';
echo '</li>';
}
?>
EDITED:
<?php
include('db.php');
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
$result = mysql_query("SELECT * FROM products where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
else
{
$start=0;
$limit=6;
if(isset($_GET['id']))
{
$id = $_GET['id'];
$start = ($id-1)*$limit;
}
$result = mysql_query("SELECT * FROM products LIMIT $start, $limit");
}
while($row = mysql_fetch_array($result))
{
echo '<li class="portfolio-item2" data-id="id-0" data-type="cat-item-4">';
echo '<div>
<span class="image-block">
<a class="example-image-link" href="reservation/img/products/'.$row['imgUrl'].'" data-lightbox="example-set" title="'.$row['Product'].'""><img width="225" height="140" src="reservation/img/products/'.$row['imgUrl'].'" alt="'.$row['Product'].'" title="'.$row['Product'].'" />
</a>
</span>
<div class="home-portfolio-text">
<h2 class="post-title-portfolio"><font color="#666666">'.$row['Product'].'</font></h2>
<p class="post-subtitle-portfolio"><font color="#666666">Descrição: '.$row['Description'].'
<p class="post-subtitle-portfolio"><font color="#666666">Categoria: '.$row['Category'].'
<p class="post-subtitle-portfolio">Código: '.$row['Price'].'</p><br/></font></p>
</div>
</div>';
echo '</li>';
}
echo "</ul>";
$rows = mysql_num_rows(mysql_query("SELECT * FROM products"));
$total = ceil($rows/$limit);
if($id>1)
{
echo "<center><a href='?id=".($id-1)."' class='button'>Anterior</a></center>";
}
if($id!=$total)
{
echo "<center><a href='?id=".($id+1)."' class='button'>Próximo</a></center>";
}
?>

You should have something like this:
// declare a base query
$q = "SELECT * FROM products";
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
// append filter to query
$q += "where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
// check for "page" URL parameter, if not available, go to first page
$page = isset($_GET['page']) ? $_GET['page'] : 1;
// check for "pageSize" URL parameter, if not available, fall back to 20
$pageSize = isset($_GET['pageSize']) ? $_GET['pageSize'] : 20;
// append the pagination to your query
$q += sprintf("LIMIT %d,%d;", ($page-1)*$pageSize, $pageSize);
// execute the constructed query
$result = mysql_query($q);
Note that the code is "pseudoish", not tested, but should give you the base idea.
Also, you can check this SO post about pagination with MySQL.
UPDATE
In PHP if you use an uninitialized variable, then it will have a context-dependent default value. See the documentation about this here. Here is an extract:
It is not necessary to initialize variables in PHP however it is a
very good practice. Uninitialized variables have a default value of
their type depending on the context in which they are used - booleans
default to FALSE, integers and floats default to zero, strings (e.g.
used in echo) are set as an empty string and arrays become to an empty
array.

Related

how to sort post titles under their correct category names PHP and SQL

I have searched for about 4 hours today on how to do this.
I want to pull all post titles and categories from the posts table and
essentially want to list the "Funny" category and then list all post that have the funny category under that category. Right now I am getting the following:
Funny
-post title
Funny
-post title
I want to output
Funny
-post title
-post title
<?php
$query = "SELECT post_category,post_title FROM posts ";
$select_categories_sidebars = mysqli_query($connection, $query);
?>
<h4>Blog Categories</h4>
<div class="row">
<div class="col-lg-12">
<ul class="list-group">
<?php
while($row = mysqli_fetch_assoc($select_categories_sidebars)) {
$post_title = $row['post_title'];
$post_tags = $row['post_category'];
echo "<li class='list-group-item'>$post_tags</li><ul>";
echo "<li class='list-group-item'><a href='category.php?category=$post_title'> {$post_title}</a></li></ul>";
}
?>
</ul>
That should do the trick:
First you should sort your query by category:
$query = "SELECT post_category,post_title FROM posts ORDER BY post_category";
Then do this:
<?php
while($row = mysqli_fetch_assoc($select_categories_sidebars)) {
$post_title = $row['post_title'];
$post_tags = $row['post_category'];
$used_tag = null,
// check if you already posted that category/tag. If not, show it:
if($used_tag!=$post_tags) {
echo "<li class='list-group-item'>$post_tags</li>"; // I removed a '</ul>' here
// set this title as 'used'
$used_tag=$post_tags;
}
echo "<li class='list-group-item'><a href='category.php?category=$post_title'> {$post_title}</a></li>"; // I removed a '</ul>' here too
}
?>
BUT
In an ideal world you'd have two tables to accomplish this.
One for the categories, one for the posts. Each table with id's to work with
This way you produce a lot of redundant data, it's more complicated to filter, and so on...
You might want to have a look at relational database design.
Well I basically got it working how I want I just need to format it correctly now, but it is working with some help from this question. PHP Group sql query under the same title
<?php
$query = "SELECT post_category,post_title FROM posts ORDER BY post_tags";
$select_categories_sidebars = mysqli_query($connection, $query);
?>
<h4>Blog Categories</h4>
<div class="row">
<div class="col-lg-12">
<ul class="list-group">
<?php
$title = "";
while ($row = mysqli_fetch_array($select_categories_sidebars)) {
if ($row['post_category'] != $title) {
echo '<li class="list-group-item">'.$row['post_category'].'</li><br>';
$title = $row['post_category'];
}
echo '<li class="list-group-item">'.$row['post_title'];
}
?>

Get the ID of my clicked product

I'm new to this site and wondering if somebody could help. I'm creating a website using bootstrap. I added some products in my DB and have used a while loop to display them on the page.
If you click on one of the products it takes you too a new page which should display all the information from only that product.
if ($select_db) {
$SQL = "SELECT * FROM products";
$result = mysql_query($SQL);
?>
<?php
$c = 0;
$id = -1; // The counter
$n = 3; // Each Nth iteration would be a new table row
while ($db_field = mysql_fetch_assoc($result)) {
$itemName = $db_field['name'];
$itemDescription = $db_field['description'];
$itemPrice = $db_field['price'];
$myPic = $db_field['image_name'];
if ($c % $n == 0 && $c != 0) { // If $c is divisible by $n...
echo '<div class="row" ></div>';
}
$c++;
$id++;
?>
<div class="col-md-4 col-sm-4" style="background-color:lavender;" id = 1>
<a href="productInfo.php">
<p> <?php echo $c ?> </p>
<h2> <?php echo $itemName ?> </h2>
<p><img class="img-responsive" img src= '<?php echo $myPic ?>' alt="Oops, Image cannot be found!" height="300" width="300"/></p>
<h3><?php echo $itemDescription ?></h3>
<p><?php echo $itemPrice ?></p>
<div id="selector" class="btn-group">
<button type="button" class="btn btn-primary" id="<?php $id ?>">Add</button>
</div>
<?php
$productsArray[] = array(
"id" => $id,
"itemName" => $itemName,
"itemDescription" => $itemDescription,
"price" => $itemPrice
);
//$_SESSION['sessionArray']=$productsArray;
?>
</a>
</div>
<?php
Now when I click on one of the columns it takes me to productInfo.php. I'm stuck as to how to display the product that is clicked?
I have added a variable $id which is the same as the array, example array [0] has id of 0, array [1] has id of 1. I think I'm trying to say if ID = 0 then display the results in the array at place [0]. I'm not sure if this helps?
I tried to display just the $id for now on productInfo.php but it only shows the last $id in the array
<?php
session_start();
if (isset($_SESSION["id"])) {
$newID = $_SESSION["id"];
echo $newID;
}
?>
I know this because it doesn't know which one I'm selecting. Am I making this too complicated?
Any help would be appreciated greatly!
Within your while loop I would add:
View More
This would concatenate the value of $id++ into the href under each item. Then all you need to do is create a landing page for product_page.php, define the $id on that page again and pull the data for that product from the db. You can do this without using any arrays.
Edit:
You would define $id on your product_page.php using $_GET['id'], as it is in the url, supplied by your href above ^
A good practice to get into whilst in the development stages would be to echo $id; to see if it is echoing the correct data from your while loop. If it echo's the correct $id then you can send the $id to the url through the href.
Let me know if this works or not.
Pulling data from db of your ID:
$sql = "SELECT * FROM table WHERE id='".$myID."'";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
$data1 = $row['whatever'];
echo $data1;

Getting only last message for each user

I am doing PM system for my site. I created subpage for each conversation by two users. I am having hard time programming the front page, where all conversations are printed. I cant get only one and last meassage for each user.
Here is my function:
public function fetch_data($id_uporabnika) {
global $pdo;
$query = $pdo->prepare("SELECT * FROM zs WHERE za = ? ORDER BY datum");
$query->bindValue(1, $id_uporabnika);
$query->execute();
return $query->fetchAll();
}
And here is my code for printing conversations:
<?php
} else {
$zs = new Zs;
$id_uporabnika = $trenutni['id'];
$zsji = $zs->fetch_data($id_uporabnika);
?>
<h2>Zasebna sporočila</h2>
<ul class="vsi-zsji">
<?php foreach ($zsji as $sporocilo): ?>
<?php $od = $oseba->fetch_data($sporocilo['od']) ?>
<li>
<a href="<?php echo $url; ?>zs/poglej/<?php echo $sporocilo['od']; ?>">
<img src="<?php echo $url; ?>inc/timthumb.php?src=<?php echo $od['slika_potem'] ?>&w=60&h=60" alt="">
<p><b><?php echo $od['uporabnisko_ime'] ?></b></p>
<p><?php echo $sporocilo['vsebina'] ?></p>
</a>
</li>
<?php endforeach ?>
</ul>
<?php } ?>
I get 10 PMs from one user, 3 for another. I want to display just the latest one.
Just put a LIMIT clause in your SQL query and order by DESC to get the latest message:
$query = $pdo->prepare("SELECT * FROM zs WHERE za = ? ORDER BY datum DESC LIMIT 1");
something like this should help
SELECT id,datum, max(pm) FROM zs WHERE za = ? group by id,datum

Display data for specific ID

I have been trying for a while to figure out how to display data from a specific row within my database based on the ID.
Say I want the link to be survivaloperations.net/page/mso?p=contracts&id=#
where id=# is the ID of the row I am pulling data from in the database
How would I pull and display data from the database using a link like shown above?
I Tried to google it, but didn't really know what to google to find related things
Any help or links for references are appreciated!
Here is what I had tried:
<?php
if ($p == contracts) {
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0; // if $_GET['id'] exists, return it as an integer, otherwise use a sentinel, id's usually start with 1, so 0 works
if ($id != 0):
// I assume this is a specific news item meaning you know it's ONE result
$query = 'SELECT * FROM contracts WHERE id=' . $id . ' LIMIT 1'; // so try to use limit 1, no need to add extra steps in the database lookup
endif;
mysql_select_db('survival_contracts');
$result = mysql_query($query);
//$result = mysql_query($query) or die(mysql_error());
// now loop through the results
while ($row = mysql_fetch_array($result)) {
// and use'em however you wish
echo("<div class='mso_body_wrap'>
<div id='mso_news_container'>
<div class='mso_news_wrap'>
<div class='mso_news_top'>$row2[contract_type]</div>
<div class='mso_news_poster'>
<div class='mso_poster_avatar'><img src='images/tank.jpg'></div>
<div class='mso_poster_info'>for <a
href='#'>$row2[unit]</a><br/>by: <a
href='http://www.survivaloperations.net/user/$row2[userid]-$row2[username]/'>$row2[username]</a>
</div>
</div>
<div class='mso_news_content'>
<div class='mso_news_body'>
Callsign: $row2[callsign]<br/>
Urgency: $row2[urgency]<br/>
Location: $row2[location]<br/>
Grid: $row2[grid]<br/>
Enemy Activity: $row2[enemy_activity]<br/>
Hours Since Lasrt Contact: $row2[contact_hours]<br/><br/>
Supplies Requested: $row2[supplies]<br/>
Comments: $row2[comments]
</div>
</div>
<div class='mso_news_bottom'></div>
</div>
</div>");
}
?>
I figured it out with my original code:
if ($p == contracts)
{
$cid = $_GET['id']; // if $_GET['id'] exists, return it as an integer, otherwise use a sentinel, id's usually start with 1, so 0 works
$query = 'SELECT * FROM contracts WHERE id='. $cid .' LIMIT 1'; // so try to use limit 1, no need to add extra steps in the database lookup
mysql_select_db('survival_contracts');
$result = mysql_query($query);
//$result = mysql_query($query) or die(mysql_error());
// now loop through the results
while($row = mysql_fetch_array($result)){
// and use'em however you wish
echo ("<div class='mso_body_wrap'>
<div id='mso_news_container'>
<div class='mso_news_wrap'>
<div class='mso_news_top'>$row[contract_type]</div>
<div class='mso_news_poster'>
<div class='mso_poster_avatar'><img src='images/tank.jpg'></div>
<div class='mso_poster_info'>for <a href='#'>$row[unit]</a><br />by: <a href='http://www.survivaloperations.net/user/$row[userid]-$row[username]/'>$row[username]</a></div>
</div>
<div class='mso_news_content'>
<div class='mso_news_body'>
Callsign: $row[callsign]<br />
Urgency: $row[urgency]<br />
Location: $row[location]<br />
Grid: $row[grid]<br />
Enemy Activity: $row[enemy_activity]<br />
Hours Since Lasrt Contact: $row[contact_hours]<br /><br />
Supplies Requested: $row[supplies]<br />
Comments: $row[comments]
</div>
</div>
<div class='mso_news_bottom'></div>
</div>
</div>");
}
Google for $_GET variable in PHP and have a look at database connection using PDO or mysqli
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/pdo.query.php
After you added code:
mysql_* is deprecated. Try to switch to either mysqli or PDO and have a look at the link above.
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT) ? abs( (int) $_GET['id']) : 0;
if($id == 0) {
echo 'Invalid ID';
return;
} else {
$query = "SELECT * FROM `table` WHERE `id`=". $id;
$get = $db->prepare($query);
if($get) {
$get = $db->query($query);
$r = $get->fetch_array(MYSQLI_ASSOC);
var_dump($r);
} else {
echo 'Could not connect to the database';
return;
}
I've mixed two styles of MySQLi, which isn't really standard, but it should suffice for this example.
http://php.net/mysqli
(Ensure you have database connection)
$row2 should be $row
And things like
$row[contract_type]
Better to be
$row['contract_type']
And try to move to mysqli or PDO as advised by earlier poster

How I can do client side pagination for DIV elements generated from MYSQL query?

I have this PHP code :
$query = "SELECT * FROM news WHERE news_active = 1 AND news_type = 1 ORDER BY id DESC";
$q2 = "SELECT * FROM st_photos WHERE id = 4 LIMIT 1";
$r2 = mysql_query($q2);
$row22 = mysql_fetch_array($r2);
$news_set = mysql_query($query);
$news_set2 = mysql_query($query);
if (mysql_num_rows($news_set) != 0) {
$r = mysql_fetch_array($news_set);
echo "<div id=\"d_coll\">
<div id=\"top_text\">$row22[img]</div>
<div id=\"d_image\"><img id=\"larg_p2\" src=\"photos/$r[news_image]\" width=\"320\" height=\"250\" border=\"0\"></div>
<div style=\"width:300px\"><div id=\"n_text2\">$r[news_part_en]</div>
</div>
</div>";
}
if (mysql_num_rows($news_set2) != 0) {
while ($news = mysql_fetch_array($news_set2)) {
echo "<div id=\"n_col\">
<div id=\"n_tittle\">$news[news_tittle_en] <img src=\"images/bu3.png\" border=\"0\" align=\"middle\"></div>
<div id=\"im\"><img onMouseOver=\"MM_swapImage('larg_p2','','photos/$news[news_image]','imgs[$news[id]]','','photos/$news[news_image]',1);up2('$news[news_part_en]')\" onMouseOut=\"MM_swapImgRestore()\" name=\"imgs[$news[id]]\" id=\"imgs[$news[id]]\" src=\"photos/$news[news_image]\" width=\"50\" height=\"50\"></div>
<div dir=\"ltr\" id=\"n_div\">$news[news_part_en] <div class=\"mo\">MORE</div></div>
</div>";
}
echo "<div align=\"right\" class=\"arr\"><img src=\"images/prev.png\"> <img src=\"images/next.png\"></div>";
}
There are 2 images at the end of the code (prev & next), I want to use them to do pagination but I don't want to view any numbers, only these 2 images.
How I can do that?
I think we can do that by using JQuery library, but I don't know how to use it.
Thanks in advance.
you can use one of many plugins, for example here .
you must just remoove thе numbers. you can, i believe;)
or you can write the script by yourself.
i'll give you only an idea. let's assume you have 30 rows( from DB).put them into <div> tags, and increase the id of div. the display proparty of first <div> you must set to '', and all others to none. and then, onclick on your buttons, you just change display proparty of div elements...

Categories