Pagination Php not working when different sql query conditions are added - php

Hello I am facing a problem with my pagination system, where if I list results from a mysql table it is working fine, but in case If I add some conditions inside the SQL Query like "AND" this column "AND" other column the script shows the results properly on the first page, when I chooce the second page instead of showing the second portion of results from 26 forward it is starting a new pagination and it is showing everything from the begining without the contions added inside the query. Here is the code of the pagination with the query:
//This gets all the other information from the form
$ciudad=$_POST['ciudad'];
$tipo=$_POST['tipo'];
$con=mysqli_connect();
// Check connection
$sql = "SELECT * FROM cursos WHERE 1";
if (!empty($ciudad)) {
$sql .= " AND ciudad = '$ciudad' ";
}
if (!empty($tipo)) {
$sql .= " AND tipo= '$tipo' ";
}
if (!$result = mysqli_query($con,$sql))
{
die("Error: " . mysqli_error($con));
}
$per_page =25;//define how many games for a page
$count = mysqli_num_rows($result);
$pages = ceil($count/$per_page);
if(!isset($_GET['page']) || $_GET['page']=="") {
$page="1";
} else {
$page=$_GET['page'];
}
$start = ($page - 1) * $per_page;
$sql = "SELECT * FROM cursos WHERE 1 LIMIT $start,$per_page";
?>
This is the code of the generated pages links:
<?php
//Show page links
for ($i = 1; $i <= $pages; $i++)
{?>
<li id="<?php echo $i;?>"><?php echo $i;?></li>
<?php
}
?>

The 2 problems where:
additional filter are not anymore selected in the next page ($_POST will be empty)
instructions related to pagination where calculated AFTER the query (which, obviously, couldn't use theses parameters)
You can either store your extra queries conditions in session, or add it as parameter in the "next page link", or transform your link to a submit form (which is probably the best option)
<li id="<?php echo $i;?>"><?php echo $i;?></li>
If you choose the link solution, don't forget to change your _POST in _GET (or check the second if the first is empty, or use $_REQUEST)
I have to mention your code is not sql injection free and using mysqli_prepare() may worth the time (for security and performances)
EDIT: so, here we go:
sidenotes: using $_REQUEST is not always recommended
And I noticed also you execute your query BEFORE using the pagination system...
//This gets all the other information from the form
$ciudad=$_REQUEST['ciudad'];
$tipo=$_REQUEST['tipo'];
$con=mysqli_connect();
// Check connection
$sql = "SELECT * FROM cursos WHERE 1";
if (!empty($ciudad)) {
$sql .= " AND ciudad = '$ciudad' ";
}
if (!empty($tipo)) {
$sql .= " AND tipo= '$tipo' ";
}
// PAGINATION MOVED UP
$per_page =25;//define how many games for a page
$count = mysqli_num_rows($result);
$pages = ceil($count/$per_page);
if(empty($_GET['page'])) {
$page="1";
} else {
$page=$_GET['page'];
}
$start = ($page - 1) * $per_page;
$sql .= ' LIMIT '.$start.','.$per_page;
if (!$result = mysqli_query($con,$sql))
{
die("Error: " . mysqli_error($con));
}
//Show page links
for ($i = 1; $i <= $pages; $i++)
{?>
<li id="<?php echo $i;?>"><?php echo $i;?></li>
<?php
}
?>

If $ciudad and $tipo both are not empty your query on execution will look like this:
SELECT * FROM cursos WHERE 1 AND ciudad = '$ciudad' ORDER BY id DESC AND tipo= '$tipo' ORDER BY id DESC
It should be like this if i am not mistaken:
SELECT * FROM cursos WHERE 1 AND ciudad = '$ciudad' AND tipo= '$tipo' ORDER BY id DESC
What I would do is change this:
$sql = "SELECT * FROM cursos WHERE 1";
if (!empty($ciudad)) {
$sql .= " AND ciudad = '$ciudad' ORDER BY id DESC ";
}
if (!empty($tipo)) {
$sql .= " AND tipo= '$tipo' ORDER BY id DESC ";
}
too this:
$sql = "SELECT * FROM cursos WHERE 1 ";
if (!empty($ciudad)) {
$sql .= "AND ciudad= '$ciudad' ";
if (!empty($tipo)) {
$sql .= "AND tipo= '$tipo' ";
}
$sql .= "ORDER BY id DESC ";
}
I've also got a link which might help you out with the pagination.
http://www.phpjabbers.com/php--mysql-select-data-and-split-on-pages-php25.html

If city and type are set then your SQL will have two instances of order by... You should add order by after the if statements.

Related

Pagination (mysql+php) on results dependent on drop-down menu filters

I have this current query, and I am desperately trying to get the results paginated (total list - if no filters are applied by using the drop down menus is about 6000 rows), but don't know how. I've tried several tutorials already, but I keep getting my full list displayed, so the ceil() function never comes into play.
I think it is because my query isn't built to allow for a simple count on total rows in the query due to the pull down menus.
Can anyone help me build the pagination around this query?
$sql = "SELECT official_status, official_expiration_date, membership_status,membership_expiration_date, player_number, first_name, last_name, classification, gender, birth_year, rating, rating_effective_date, country, code, country.description, bracket.id, bracket.min, bracket.max, cutoff FROM Players, country, bracket, ratingscutoff WHERE membership_expiration_date >= cutoff AND Players.country = country.code ";
if (!empty($_GET['class'])) {
$filter_class = $_GET['class'];
$sql .= "AND classification = '{$filter_class}' ";
}
if (!empty($_GET['gender'])) {
$filter_gender = $_GET['gender'];
$sql .= "AND gender = '{$filter_gender}' ";
}
if (!empty($_GET['country'])) {
$filter_country = $_GET['country'];
$sql .= "AND country = '{$filter_country}' ";
}
if (empty($_GET['bracket'])) {
$filter_bracket = $_GET['bracket'];
$sql .= "AND bracket.id = '0' AND Players.birth_year BETWEEN bracket.min AND bracket.max ";
}
else
{
if (!empty($_GET['bracket'])) {
$filter_bracket = $_GET['bracket'];
$sql .= "AND bracket.id = '{$filter_bracket}' AND Players.birth_year BETWEEN bracket.min AND bracket.max ";
}
}
$sql .= "ORDER BY rating DESC, player_number ASC";
$result = mysqli_query($link, $sql) or die("Unable to select: ".mysqli_error());
$num_rows = mysqli_num_rows($result);
$counter = 1;
while ($row = mysqli_fetch_array($result)) {
printf("<tr>
<td class=\"stats\">$counter</td>
<td nowrap class=\"stats\"><b>%s %s <img src=\"/wp-content/uploads/2014/12/%s.png\" title=\"certified official until %s\"/></b>
</td>
<td class=\"stats\"><span title=\"current member through %s\">%s</span></td>
<td class=\"stats\"><span title=\"rating updated %s\">%s</span></td>
<td class=\"stats\">%s</td>
<td class=\"stats\">%s</td>
<td class=\"stats\">%s</td>
\n",
$row["player_number"], $row["first_name"], $row["last_name"], $row["official_status"], $row["official_expiration_date"], $row["membership_expiration_date"], $row["player_number"], $row["rating_effective_date"], $row["rating"], $row["classification"], $row["gender"], $row["description"]);
$counter++; //increment counter by 1 on every pass
}
For pagination, in most cases you need 2 queries, a first that counts the total number of rows, and the second that actually returns the rowset using a LIMIT with the last offset and the number of rows per page.
Basically the 2 queries are the same, the first one being just a COUNT(). Run it, to get the total (I set it in a $num_rows variable in my example), then set a variable to have your number of rows per page (let's say $rows_per_page = 10;), and then before the scond query, do something like:
if (empty($_GET['page'])) {
$page = 1;
$offset = $rows_per_page;
} else {
$num_pages = floor($num_rows / $rows_per_page);
if ($_GET['page'] > $num_pages) {
$page = $num_pages;
} else {
$page = $_GET['page'];
}
$offset = $rows_per_page * $page;
}
You have your limits now for the second query:
LIMIT '.$offset.', '.$rows_per_page
UPDATE: I quickly wrote something using your code, it should work with minor changes (not tested)
$rows_per_page = 10;
$sql_count = "
SELECT
COUNT(*)
FROM
Players, country, bracket, ratingscutoff
WHERE membership_expiration_date >= cutoff
AND Players.country = country.code
";
$result_count = mysqli_query($link, $sql_count) or die("Unable to select: ".mysqli_error());
$num_rows = mysqli_num_rows($result_count);
if (empty($_GET['page'])) {
$page = 1;
$offset = $rows_per_page;
} else {
$num_pages = floor($num_rows / $rows_per_page);
if ($_GET['page'] > $num_pages) {
$page = $num_pages;
} else {
$page = $_GET['page'];
}
$offset = $rows_per_page * $page;
}
// Your other filters are being omitted for more clarity
$sql_select = "
SELECT
official_status, official_expiration_date, membership_status,membership_expiration_date, player_number, first_name, last_name, classification, gender, birth_year, rating, rating_effective_date, country, code, country.description, bracket.id, bracket.min, bracket.max, cutoff
FROM
Players, country, bracket, ratingscutoff
WHERE membership_expiration_date >= cutoff
AND Players.country = country.code
ORDER BY rating DESC, player_number ASC
LIMIT ".$offset.", ".$rows_per_page."
";
$result = mysqli_query($link, $sql_select) or die("Unable to select: ".mysqli_error());

Next image link loop

I'm trying to get my next images in a loop so they go back to the start of the the image list. I am able to get the images to go through the list right up to the last image then my last image shows no PID on the link.
I have
<div id="photolistholder">
<?php if(isset($_GET['pid'])){?>
<?php
//Now we'll get the list of the specified users photos
$var =$_GET['pid'];
$sql = "SELECT * FROM coverphotos WHERE coverphoto_id='$var'";
$query = mysqli_query($mysqli,$sql)or die(mysqli_error($mysqli));
while($photo = mysqli_fetch_array($query)){
$user=rawfeeds_user_core::getuser($photo['coverphoto_userid']);
?>
<p class="frontpage_description"><a href="profile.php?username=<?php echo $user['username']; ?>">
<?php
$id=$_SESSION['id'];
if($user['id']){
echo "<img border=\"0\" src=\"userimages/cropped".$user['id'].".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" ><br/>".$user['fullname']."'s</a> Album: </p>";
}else{
echo "<img border=\"0\" src=\"userimages/cropped".$id.".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" ><br/>".$user['fullname']." </a></p>";
}
$id=$_SESSION['id'];
$var = $_GET['pid'] ;
$photo_sql = "SELECT coverphoto_id FROM coverphotos WHERE (coverphoto_id < ".$var." OR coverphoto_id > ".$var.") AND coverphoto_userid = ".$user['id']." ORDER BY coverphoto_id DESC LIMIT 1";
$photo_query = mysqli_query($mysqli,$photo_sql)or die(mysqli_error($mysqli));
$photo_prev=mysqli_fetch_array($photo_query);
if($photo_prev>1){
echo"<a href='coverimagephoto.php?pid=".$photo_prev['coverphoto_id']."'>Previous</a> | ";
}else{
echo " ";
}
$var = $_GET['pid'] ;
$photo_sqls = "SELECT coverphoto_id FROM coverphotos WHERE (coverphoto_id > ".$var." OR coverphoto_id < ".$var.") AND coverphoto_userid = ".$user['id']." ORDER BY coverphoto_id ASC LIMIT 1";
$photo_querys = mysqli_query($mysqli,$photo_sqls)or die(mysqli_error($mysqli));
$photo_next=mysqli_fetch_array($photo_querys);
if($photo_next>1){
echo "<a href='coverimagephoto.php?pid=".$photo_next['coverphoto_id']."'>Next</a>";
}else{
echo "";
}
$user1_id=#$_SESSION['id'];
$user2_id=$user['id'];
if($user1_id==#$_SESSION['id']){
echo " | <a href='include/photo_delete.php?pid=".$photo['coverphoto_id']."'>Delete</a>";
}else{
echo"";
}
?>
<center>
<?php
//echo "<div class='photo_captionholder'><b>Name</b> : ".$photo['photo_name']." | <b>Caption</b> : ".$photo['photo_caption']." |
//<b>Uploaded</b> : ".$photo['photo_datetime']."</div>";
echo "<img id=\"coverimage\" border=\"0\" src='coverimages/".$photo['coverphoto']."?".time()."' onerror='this.src=\"coverimages/nocover.png\"'>";
}}
?>
</body>
I tried using
$var = $_GET['pid'] ;
$photo_sql = "SELECT coverphoto_id FROM coverphotos WHERE (coverphoto_id > ".$var." OR coverphoto_id < ".$var.") AND coverphoto_userid = ".$user['id']."";
$photo_query = mysqli_query($mysqli,$photo_sql)or die(mysqli_error($mysqli));
$photo_next=mysqli_fetch_array($photo_query);
if($photo_next>1){
echo"<a href='coverimagephoto.php?pid=".$photo_prev['coverphoto_id']."'>Next</a> | ";
}else{
echo " ";
}
But the link just jumps between two images. The images are not in 1,2,3,4,5 they can be 1,2,4,5 if a user deletes an image and it can start on image PID 3 or 5.
Would it not be much simpler to code and understand and also reduce your queries (round trips to the server and back) from N+1 queries to 1 query where N=(number of photos) if you just used the first query and then fetched all the results into an array, and then process up and down that array
Quick mockup:
<div id="photolistholder">
<?php
if( isset($_GET['pid']) ) {
// validate the pid
$_GET['pid'] = some_validation_please($_GET['pid']);
$id=$_SESSION['id'];
$sql = "SELECT * FROM coverphotos WHERE coverphoto_id='$_GET['pid']'";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
$photos = array();
while($row = mysqli_fetch_array($result)){
$photos[] = $row;
}
foreach( $photos as $idx => $photo ) {
// add all your image html with the prev and next links
// using $idx-1 for prev image
// using $idx+1 for next image
// and checking if $idx = 0 for first image
// so you can use count($photos)-1 to know you are on last image
// so you use photos[0] as the next image to get continuous loop
// and if $idx == 0 next image is count($photos)-1
}
?>
Sorry I have not got the time to pick the bones out of what you are putting out to the browser, as I am bound to make a silly mistake and get hassled for it.
I have figured out a better way that works perfectly. Just use a UNION
$var = mysqli_escape_string($_GET['pid']) ;
$photo_sql = "(SELECT coverphoto_id FROM coverphotos WHERE coverphoto_id < ".$var." AND coverphoto_userid = ".$user['id']." AND album=1 ORDER BY coverphoto_id DESC LIMIT 1)";
$photo_sql.= " UNION (SELECT coverphoto_id FROM coverphotos WHERE coverphoto_id > ".$var." AND coverphoto_userid = ".$user['id']." AND album=1 ORDER BY coverphoto_id DESC LIMIT 1)";
$photo_query = mysqli_query($mysqli,$photo_sql)or die(mysqli_error($mysqli));
$photo_prev=mysqli_fetch_array($photo_query);
if($photo_prev>1){
echo"<a href='coverimagephoto.php?pid=".$photo_prev['coverphoto_id']."'>Previous</a> | ";
}else{
echo " ";
}
$var = $_GET['pid'] ;
$photo_sqls = "(SELECT coverphoto_id FROM coverphotos WHERE coverphoto_id > ".$var." AND coverphoto_userid = ".$user['id']." AND album=1 ORDER BY coverphoto_id ASC LIMIT 1)";
$photo_sqls.= " UNION (SELECT coverphoto_id FROM coverphotos WHERE coverphoto_id < ".$var." AND coverphoto_userid = ".$user['id']." AND album=1 ORDER BY coverphoto_id ASC LIMIT 1)";
$photo_querys = mysqli_query($mysqli,$photo_sqls)or die(mysqli_error($mysqli));
$photo_next=mysqli_fetch_array($photo_querys);
if($photo_next>1){
echo "<a href='coverimagephoto.php?pid=".$photo_next['coverphoto_id']."'>Next</a>";
}else{
echo " ";
}

PHP Select from multiple tables and add value together to get total

i am trying to run these queries in PHP to a mysql table
$sql="SELECT * from customer where customerid > '' and voicemail_max > '' and company_status = '' ";
$rs=mysql_query($sql,$conn);
while($customer=mysql_fetch_array($rs)) {
$sql2="SELECT * from client where parent_client_id = '".$customer["customerid"]."' ";
$rs2=mysql_query($sql2,$pbx01_conn);
while($result2=mysql_fetch_array($rs2))
{
$sql3="SELECT * from extension where client_id = '".substr($result2["id"],1,3)."' ";
$rs3=mysql_query($sql3,$pbx01_conn);
while($result3=mysql_fetch_array($rs3))
{
$sql4="SELECT * from extension_voicemail where extension_id = '".$result3["id"]."' ";
$rs4=mysql_query($sql4,$pbx01_conn);
$voicemail_size_total=0;
while($result4=mysql_fetch_array($rs4)) {
$voicemail_size_total = $voicemail_size_total+$result4["filesize"];
}
}
}
echo $voicemail_size_total;
}
it should be adding up multiple values from one column
the $sql4 query looks like:
SELECT * from extension_voicemail where extension_id = '1454'
and when i run that in the database, it returns one row with the file size column as 31780
but when i echo $voicemail_size_total variable, it shows nothing.
it works fine if i echo that variable one line up from where it is, but where it is now shows nothing
Declare $voicemail_size_total=0; outside of all of the while loops. Everytime you get back to the loop you re-set that back to 0. That might be the problem.
Well, it depends on what you want to achieve:
1. If you want to get a total of all the filesizes (basicly you are expecting just one value to be presented ) try this:
$sql="SELECT * from customer where customerid > '' and voicemail_max > '' and company_status = '' ";
$rs=mysql_query($sql,$conn);
$voicemail_size_total=0;
while($customer=mysql_fetch_array($rs)) {
$sql2="SELECT * from client where parent_client_id = '".$customer["customerid"]."' ";
$rs2=mysql_query($sql2,$pbx01_conn);
while($result2=mysql_fetch_array($rs2))
{
$sql3="SELECT * from extension where client_id = '".substr($result2["id"],1,3)."' ";
$rs3=mysql_query($sql3,$pbx01_conn);
while($result3=mysql_fetch_array($rs3))
{
$sql4="SELECT * from extension_voicemail where extension_id = '".$result3["id"]."' ";
$rs4=mysql_query($sql4,$pbx01_conn);
while($result4=mysql_fetch_array($rs4)) {
$voicemail_size_total = $voicemail_size_total+$result4["filesize"];
}
}
}
}
echo $voicemail_size_total;
2. If you're looking for the filesizes of each client (ie. expecting a series of filesizes to be presented ) try this:
$sql="SELECT * from customer where customerid > '' and voicemail_max > '' and company_status = '' ";
$rs=mysql_query($sql,$conn);
while($customer=mysql_fetch_array($rs)) {
$sql2="SELECT * from client where parent_client_id = '".$customer["customerid"]."' ";
$rs2=mysql_query($sql2,$pbx01_conn);
$voicemail_size_total=0;
while($result2=mysql_fetch_array($rs2))
{
$sql3="SELECT * from extension where client_id = '".substr($result2["id"],1,3)."' ";
$rs3=mysql_query($sql3,$pbx01_conn);
while($result3=mysql_fetch_array($rs3))
{
$sql4="SELECT * from extension_voicemail where extension_id = '".$result3["id"]."' ";
$rs4=mysql_query($sql4,$pbx01_conn);
while($result4=mysql_fetch_array($rs4)) {
$voicemail_size_total = $voicemail_size_total+$result4["filesize"];
}
}
}
echo $voicemail_size_total;
}

Get result from SQL Query

I've got a MySQL query based on a database of ship information, this includes a field ship_name and the key ship_id.
I've written a query which uses the current_ship_id of the page, and finds the next ship based on the alphabetical list of ship_names.
This all works fine, HOWEVER, I'm trying to create a link using the below code in the 'IF' statement.
header("Location: shipinfo.php?ship_id=$next_ship_id");
What I don't know how to do is define the variable next_ship_id. I tried the line:
$next_ship_id = ($ship_id);
In theory, I want to get the result of the query $sql (of which I know there is only one result) and find it's ship_id.
How do I do that please?
$sql = " SELECT ship_infomation.ship_id
FROM ship_infomation
INNER JOIN (
SELECT ship_name
FROM ship_infomation
WHERE ship_id = $current_ship_id
) As current_ship
ON ship_infomation.ship_name < current_ship.ship_name
ORDER BY ship_infomation.ship_name ASC
LIMIT 1";
// echo "<br /><br />$sql<br /><br />";
$ships = mysql_query($sql, $ships) or die(mysql_error());
$row_ships = mysql_fetch_assoc($ships);
$totalRows_ships = mysql_num_rows($ships);
$next_ship_id = ($ship_id);
if ($totalRows_ships = 1)
{
header("Location: shipinfo.php?ship_id=$next_ship_id");
}
else
{
// remain on current page
}
For the next ship use:
SELECT ship_id
FROM ship_infomation
WHERE ship_id = (SELECT min(ship_id)
FROM ship_infomation
WHERE ship_id > $current_ship_id)
LIMIT 1
For the previous ship use:
SELECT ship_id
FROM ship_infomation
WHERE ship_id = (SELECT max(ship_id)
FROM ship_infomation
WHERE ship_id < $current_ship_id)
LIMIT 1
And at your code change this:
$ships = mysql_query($sql, $ships) or die(mysql_error());
$row_ships = mysql_fetch_assoc($ships);
$totalRows_ships = mysql_num_rows($ships);
$next_ship_id = ($ship_id);
if ($totalRows_ships = 1)
{
header("Location: shipinfo.php?ship_id=$next_ship_id");
}
else
{
// remain on current page
}
To this:
$ships = mysql_query($sql, $ships) or die(mysql_error());
$row = mysql_fetch_assoc($ships);
$totalRows_ships = mysql_num_rows($ships);
if ($totalRows_ships = 1)
{
header("Location: shipinfo.php?ship_id=" . $row['ship_id']);
}
else
{
// remain on current page
}
For the next and previous, on your code:
$go = isset($_GET['go']) ? $_GET['go'] : 'next';
if ($go == 'next')
$sql = "SELECT ship_id FROM ship_infomation WHERE ship_id = (SELECT min(ship_id) FROM ship_infomation WHERE ship_id > ". mysql_real_escape_string($current_ship_id) . ") LIMIT 1";
else
$sql = "SELECT ship_id FROM ship_infomation WHERE ship_id = (SELECT max(ship_id) FROM ship_infomation WHERE ship_id < ". mysql_real_escape_string($current_ship_id) . ") LIMIT 1";
And on your URL have it like this for the next ship:
http://mysite.com/ships.php?current_ship_id=15&go=next
And like this for the previous:
http://mysite.com/ships.php?current_ship_id=15&go=previous
If the go is not specified it will go to the previous ship by default.
There is no more support for mysql_* functions, they are officially deprecated, no longer maintained and will be removed in the future. You should update your code with PDO or MySQLi to ensure the functionality of your project in the future.

Pagination. Select from x number of tables

i'm trying to make my second website using php and i'm stuck at some typical problem (i believe),
but very hard for me.
I'm making a page that show list of items depends on GET.
#1 if only "type" sended - show all items with x type.
#2 if only "tag" sended - show all items with x tag.
#3 if "type" and "tag" sended at the same time - show all items with x type and x tag.
problem #1 i solved this way
// items per page
$per_page = 5;
// 1) if isset type
if ( (isset($_GET['type'])) && (!isset($_GET['tag'])) ){
$type_id = get_safe_var($_GET['type']);
$con = mysql_connect(DB_HOST,DB_LOGIN,DB_PASSWORD) or die(mysql_error());
if ($con) {
mysql_select_db(DB_NAME) or die(mysql_error());
$sql = mysql_query("SELECT `item_type`, `item_type_name` FROM `item_types` WHERE `type_id` = '$type_id'");
$row = mysql_fetch_assoc($sql);
$type = $row['item_type'];
$type_name = $row['item_type_name'];
if ($type != ''){
$pages_query = mysql_query("SELECT COUNT(`id`) FROM `".$type."` WHERE `insearch` = '1'");
$number_of_pages = ceil( mysql_result($pages_query, 0) / $per_page );
$current_page = ( (isset($_GET['page'])) && ((int)$_GET['page'] > 0) ) ? (int)$_GET['page'] : 1;
$start = ($current_page - 1) * $per_page;
echo "<h1>$type_name</h1>";
$sql = mysql_query("SELECT `id`, `name`, `img` FROM `".$type."` WHERE `insearch` = '1' ORDER BY `id` DESC LIMIT $start, $per_page");
// echo items
while ($row = mysql_fetch_assoc($sql)){
$id = $row['id'];
$name = $row['name'];
$img = $row['img'];
echo "
<div id='items_cell'>
<img alt='$name' src='$img' width='145' height='200' /><br />
<a href='open_item.php?type=$type_id&id=$id'>$name</a><br />
<em>$type_name</em>
</div>";
}
}
mysql_close($con);
} else {echo 'sql connection error';}
}
pagination
// echo pagination
// 1) if isset type
if ( (isset($_GET['type'])) && (!isset($_GET['tag'])) ){
if ( (isset($number_of_pages)) && ($number_of_pages >= 1) && ($current_page <= $number_of_pages) ){
for ($i = 1; $i <= $number_of_pages; $i++){
if ($i == $current_page){
echo "<li><a href='?type=$type_id&page=$i' class='sel'>$i</a></li>";
} else {
echo "<li><a href='?type=$type_id&page=$i'>$i</a></li>";
}
}
}
}
I'm stuck at problem #2.
I got tag ID. Need to show all items with that tag.
I don't understand how to make a SELECT from x-number of tables with a working paginatin.
database structure -
Any help is welcome!
P.S. Maybe i need to change db structure to make SELECT easier?
You should definitely work on your table design. Having dynamic table names is a big NO-NO as you won't ever be able to do any useful joins. Just create one big tag-table and add a column type like you did in your table item_types.
To solve problems #1-#3 just build the WHERE-part of your query dynamically:
// empty selection
$where = array();
if (!empty($_GET["type"])
$where[] = "`item_type` = '".mysql_real_escape_string($_GET["type"])."'";
if (!empty($_GET["tag"])
$where[] = "`tag` = '".mysql_real_escape_string($_GET["tag"])."'";
$query = "SELECT ... FROM `item`"
// Join type-table
. " JOIN `item_types` ON `item`.`id` = `item_types`.`item_id`"
// Join all of this item's tags
. " JOIN `item_tags` ON `item`.`id` = `item_tags`.`item_id`"
// Filter tags by item_type
. " AND `item_types`.`item_type` = `item_tags`.`item_type`"
;
if (count($where) > 0)
$query .= "WHERE ".implode(" AND ", $where);

Categories