I am new to the whole php, sql, jquery. I am trying to paginate a sql gallery. I keep getting an error when using the sql LIMIT clause.
It either spits all the images out on one page but gives non functioning page number buttons OR only shows the selected number of items but doesnt create extra pages for the rest of the queries results.
I have searched for a solution and found that there was a problem with using variables after the LIMIT function. Can anyone either show me a better way to implement this or give me a solution to my problem.
$items = 8;
if(isset($_GET['page']) and is_numeric($_GET['page']) and $page = $_GET['page'])
$limit = " LIMIT ".(($page-1)*$items).",$items";
else
$limit = " LIMIT $items";
if(empty($clothing) && empty($price) && empty($uploaded)) {
$query = "SELECT path, description, filename FROM category $limit";
$result = mysql_query($query) or die(mysql_error());
I have also tried this below which gives an error.
$per_page = 8;
if(isset($_GET['page']))
{
$page=$_GET['page'];
}
$start = ($page-1)*$per_page;
if(empty($clothing) && empty($price) && empty($uploaded)) {
$query = "SELECT path, description, filename FROM category LIMIT $start, $per_page ";
$result = mysql_query($query) or die(mysql_error());
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-8, 8' at line 1.
To shed more light the 'if' is to filter the queries results. This is just the first of many sql queries.
Thanks
Offset value for LIMIT cannot be negative
Related
I want to get the ID of an image that is boostAmount-boostStart>total. Currently if an image exists that is appropriate it works. However, if there is nothing appropriate to show I get this error.
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY RAND() LIMIT 1' at line 1
$photoToGuess = mysql_query("SELECT photoID,id,total,boostStart,boostAmount,auth,photoUploadDate FROM photos WHERE (boostAmount !=0) AND ((boostAmount-boostStart)>total) AND (auth=2 OR auth=5 OR auth=7) ORDER BY RAND() LIMIT 1") or die("Invalid query: " . mysql_error());
$getphotoToGuess = mysql_fetch_array($photoToGuess);
//Yes
if(mysql_num_rows($photoToGuess) > 0)
{
//do something
}
Try this, I removed die condition you can achieve die condition using if statement...It is working fine chech once.
$photoToGuess = mysql_query("SELECT photoID,id,total,boostStart,boostAmount,auth,photoUploadDate FROM photos WHERE (boostAmount !=0) AND ((boostAmount-boostStart)>total) AND (auth=2 OR auth=5 OR auth=7) ORDER BY RAND() LIMIT 1");
$getphotoToGuess = mysql_fetch_array($photoToGuess);
//Yes
if(mysql_num_rows($photoToGuess) > 0)
{
//do something
}
You can refer this http://php.net/manual/en/function.mysql-query.php
Your if condition is wrong
why are you using $photoToGuess in your if conditioner code here
if(mysql_num_rows($getphotoToGuess ) > 0){
// do something
}
I am making a page that queries a table for all columns of all results ordered by entry time in descending order with a limit. When I query for a count of the rows, the query works just fine, but when I try to query the table again for data, I don't get anything. I decided to try cutting the query down to "SELECT * FROM comments" but I still got no results when "SELECT COUNT(*) AS count FROM comments" just beforehand worked. I've tried using mysqli_error(), but that didn't give me any information.
The query doesn't seem to be failing as the result from mysqli_query() isn't false and when I query in phpMyAdmin, the queries work. A little piece of my code below
//open databases
require_once($root . "databases/data.php");
//get number of suggestions in comments table
$cquery = mysqli_query($cbase, "SELECT COUNT(*) AS count FROM comments"); //this works
$c = mysqli_fetch_array($cquery);
$count = $c["count"];
//get all suggestions
//this query fails
$queryText = "SELECT * FROM comments ORDER BY time DESC LIMIT " . (($page - 1) * $pageLimit) . ", " . $pageLimit;
$query = mysqli_query($cbase, $queryText);
//validate query
if($query === false)
{
$failed = true;
}
//get all comments from query
while(!$failed && $array = mysqli_fetch_array($result))
Please try this on line 3
$c = mysqli_fetch_assoc($cquery);
You can also try like this also,
$c = mysqli_fetch_array($cquery, MYSQLI_ASSOC);
You are just using the wrong variable when reading out your query results in your while-loop. mysqli_fetch_array($result) while you saved the query-result in $query so it should be mysqli_fetch_array($query)
I have an Ajax call to create an image gallery. There is a combo box to set the number of images per page, and pagination to navigate through the pages. It's working fine, except that if a person is on the last page, and they increase the number of images per page, it reloads to the current page number. This is a problem because there are now less pages and so the page is blank. In other words, you end up on page 7 of 5 for instance.
I reckon the problem is in the PHP as that is where the number of pages is calculated. I've thought out an if statement to deal with this:
if ($page > $no_of_paginations) {
$page = $no_of_paginations;
}
However, I don't know where to place this. The reason being, $page needs to be defined before the mysql_query, but $no_of_paginations is defined after the query.
Any thoughts on how I can make this functional?
I'll post the pertinent code below:
<?php
$page = 0;
if(isset($_GET['page'])){
$page = (int) $_GET['page'];
}
$cur_page = $page;
$page -= 1;
if((int) $_GET['imgs'] > 0){
$per_page = (int) $_GET['imgs'];
} else {
$per_page = 16;
}
$start = $per_page * $page;
include"db.php";
$query_pag_data = "SELECT `imgURL`,`imgTitle` FROM `images` ".
"ORDER BY `imgDate` DESC LIMIT $start, $per_page";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
echo "<ul class='new_arrivals_gallery'>";
while($row = mysql_fetch_assoc($result_pag_data)) {
echo "<li><a target='_blank' href='new_arrivals_img/".$row['imgURL']."' class='gallery' title='".$row['imgTitle']."'><img src='new_arrivals_img/thumbnails/".$row['imgURL']."'></a></li>";
}
echo "</ul>";
/* --------------------------------------------- */
$query_pag_num = "SELECT COUNT(*) AS count FROM images";
$result_pag_num = mysql_query($query_pag_num);
$row = mysql_fetch_array($result_pag_num);
$count = $row['count'];
$no_of_paginations = ceil($count / $per_page);
?>
Thanks for your help!
As you are currently doing it, there would be no problem with moving the last section to above the main query.
A better way to find the total records with MySQL is to use the SQL_CALC_FOUND_ROWS keyword on your main query (so here it is SELECT SQL_CALC_FOUND_ROWS imgURL, imgTitle FROM images WHERE etc) then you can query SELECT FOUND_ROWS() and just get the number of records found in the last query. As well as being faster and more efficient, this avoids a race condition when records are added between the two queries.
However, in this case you should probably just do the two current queries in the reverse order as your only other option is to check at the end and repeat if necessary.
You should use query:
$query_pag_data = "SELECT SQL_CALC_FOUND_ROWS `imgURL`,`imgTitle` FROM `images` ".
"ORDER BY `imgDate` DESC LIMIT $start, $per_page";
And instead of
$query_pag_num = "SELECT COUNT(*) AS count FROM images";
use
$query_pag_num = "SELECT FOUND_ROWS()";
If you do the "SELECT COUNT(*) ..." query earlier in the script (at least before the other query), you will have $no_of_paginations earlier, and can use it to clamp $page to the correct range.
Sometimes you just have to bite the bullet and do a query twice. Accept the user-provided "I want page X" value, and try to get that particular page. If it ends up being past the end of the available data, you can either say "hey, wait... that ain't right" and abort, or redo the loop and default to the last available page.
while(true) {
$sql = "select sql_calc_found_rows .... limit $X,$Y";
$result = mysql_query($sql) or die(mysql_error());
$sql = "select found_rows();"; // retrieve the sql_calc_found_rows_value
$res2 = mysql_query($sql);
$row = mysql_fetch_array($res2);
$total_rows = $row[0];
if ($total_rows < $requested_row) {
... redo the loop and request last possible page ...
} else {
break;
}
}
details on found_rows() function here.
I have this code:
$local_id = $_GET['id'];
$sql = dbquery("SELECT * FROM `videos` WHERE `id` = ".$local_id." LIMIT 0, 1");
while($row = mysql_fetch_array($sql)){
$video_id = $row["youtube_id"];
// the rest
}
how can i check if $local_id does not exist in the db and display an error?
mysql_num_rows
if(mysql_num_rows($sql) == 0) {
//Show error
}
$sql = dbquery("select count(*) from videos where id = ".$local_id." LIMIT 0, 1");
$row = mysql_fetch_row($sql);
if($row[0] == 0)
echo 'error';
You can use the following query:
"SELECT COUNT(*) FROM `videos` WHERE `id` = ".mysql_real_escape_string($local_id)
This query will return one number: how many records have matched your query. If this is zero, you surely know that there are no records with this ID.
This is more optimal than other solutions posted in case you only want to check for the existence of the ID, and don't need the data (if you use SELECT * ..., all the data will be unnecessarily sent from MySQL to you). Otherwise mysql_num_rows() is the best choice, as #Ryan Doherty correctly posted.
Be sure to ALWAYS escape data that came from the outside (this time GET) before you put it into a query (mysql_real_escape_string() for MySQL).
If you fail to do so, you are a possible victim for SQL Injection.
You could have a $count variable and increment it in the while loop. After the loop, check the count, if it is 0, then echo an error message.
$How_Many_Manufacturers = "SELECT COUNT(manufacturer), manufacturer
FROM products
WHERE name LIKE '%$new_title%'
GROUP BY manufacturer";
$result2 = mysql_query($How_Many_Manufacturers, $connection) or die(mysql_error());
$num_rows = mysql_num_rows($result2);
if ($num_rows == 0)
{
echo "<div id=\"noMatches\">No Matches</div>";
}
else {
}
The if statement will not work.
How can I correct this script?
#Arjan You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-25,25' at line 4 -RPM
make sure you escape $new_title in the query.
$How_Many_Manufacturers = "SELECT COUNT(manufacturer), manufacturer
FROM products
WHERE name LIKE '%".mysql_real_escape_string($new_title)."%'
GROUP BY manufacturer";
SELECT COUNT will always return a row (even if the count is zero). Simply remove the COUNT, or fetch the row to see the count.