PHP MySQL giving error when applying limit to query - php

<?php
//pagination
if (isset($_GET["page"]))
{
$page = $_GET["page"];
}
else
{
$page = 1;
}
$start_from = ($page - 1) * 10;
$rowLimit = 10; //result limit
?>
<?
//full query
$query = "SELECT * FROM ".mysqli_real_escape_string($games,$_GET['type'])." ORDER BY `Name` ASC";
//query limit
$query_limit = sprintf('%s LIMIT %d %d', $query, $start_from, $rowLimit);
//run full query
$result = mysqli_query($games, $query) or die(mysqli_error($games));
//full rows
$row_all = mysqli_fetch_assoc($result);
//run limited query
$result_limit = mysqli_query($games, $query_limit) or die(mysqli_error($games));
//limited rows
$row = mysqli_fetch_assoc($result_limit);
//number of full rows
$row_all_Num = mysqli_num_rows($result);
//number of limited rows
$row_num = mysqli_num_rows($result_limit);
?>
when I try to open list.php?type=installed MySQL shows this 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 '10' at line 1
if I remove lines that apply limit query works fine but displays all results at once
where is the problem I cant find it....

Use comma between limits
or use LIMIT x OFFSET y
syntax.

echo and then die, it will print the query in your browser and paste it here for others to see.
$query = "SELECT * FROM ".mysqli_real_escape_string($games,$_GET['type'])." ORDER BY `Name` ASC";
echo $query;
die();

Related

PDO pagination with LIKE

The following PHP SQL code shows error
Recoverable fatal error: Object of class PDOStatement could not be converted to string in /home/customer/xxxx/fetch_data.php on line 28
I was trying to display products information from the table filter
There are two $statement->execute();, one is to count total search results and another one is to display products for the current page.
I new to PDO method and not an expert in overall coding.
The $filter_query = $stmt . 'LIMIT '.$start.', '.$limit.''; is causing issues.
With that and related functions, the code works and displays data. But if I enable it, the error shows up.
$limit = '5';
$page = 1;
if($_POST['page'] > 1)
{
$start = (($_POST['page'] - 1) * $limit);
$page = $_POST['page'];
}
else
{
$start = 0;
}
$search = "%samsung%";
$stmt = $connect->prepare("SELECT * FROM filter WHERE product_name LIKE :needle");
$stmt->bindParam(':needle', $search, PDO::PARAM_STR);
##
##
$filter_query = $stmt . 'LIMIT '.$start.', '.$limit.'';
$statement->execute();
$total_data = $stmt->rowCount();
$stmt = $connect->prepare($filter_query);
$stmt->execute();
$result = $stmt->fetchAll();
$total_filter_data = $stmt->rowCount();
$output = '
<h3> '.$total_data.' results found </h3>
and display each product
I tried the following code as suggested by Your Common Sense and the pagination and total search result count is working fine, but no products are getting displayed.
$limit = '5';
$page = 1;
if($_POST['page'] > 1)
{
$start = (($_POST['page'] - 1) * $limit);
$page = $_POST['page'];
}
else
{
$start = 0;
}
$name=str_replace(' ', '%', $_POST['query']);
$search = "%$name%";
$base_sql = "SELECT %s FROM filter WHERE product_name LIKE ?";
##
##
####
$count_sql = sprintf($base_sql, "count(*)");
$stmt = $connect->prepare($count_sql);
$stmt->execute([$search]);
$total_data = $stmt->fetchColumn();
####
$data_sql = $count_sql = sprintf($base_sql, "*")." LIMIT ?,?";
$stmt = $connect->prepare($data_sql);
$stmt->execute([$search, $start, $limit]);
$result = $stmt->fetchAll();
##
$output = '
<h3> '.$total_data.' results found </h3> ';
if($total_data > 0)
{
foreach($result as $row)
{
and display each product
Using the following line makes the code show some data, but the pagination is not working.
$data_sql = sprintf($base_sql, "*");
$stmt = $connect->prepare($data_sql);
$stmt->execute([$search]);
$result = $stmt->fetchAll();
That's a not a trivial task as we need to run the same query twice but with minor differences. The first query will use count(*) SQL function to get the total number of records matching the search criteria. The second query will select actual fields with LIMIT clause to get the data for the single page.
$base_sql = "SELECT %s FROM filter WHERE product_name LIKE ?";
$count_sql = sprintf($base_sql, "count(*)");
$stmt = $connect->prepare($count_sql);
$stmt->execute([$search]);
$total = $stmt->fetchColumn();
$data_sql = $count_sql = sprintf($base_sql, "*")." LIMIT ?,?";
$stmt = $connect->prepare($data_sql);
$stmt->execute([$search, $start, $limit]);
$data = $stmt->fetchAll();
Important: In order for this code to work, make sure you are connecting to mysql properly. the proper connection will let a LIMIT clause to accept placeholders and also will warn you in case of any problems.

How to select the maximum value of a column in MySQL

I want to select the maximum value of a column of my table. I'm using PHP and MySQL. This is what I have so far:
$max = "SELECT MAX(Id) FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
echo= $max1;
My debugger is just saying that it is a query returning a 0 boolean value (false). I cannot find a specific answer anywhere on the internet.
You need to fetch the data from the mysqli_result object that was returned to you when you executed your query using mysqli_query.
$max = "SELECT MAX(Id) as id FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
$row = mysqli_fetch_assoc($max1); // this was missing
$id=$row['id'];
echo $id;
Note: I removed the loop because with MAX query without any grouping you will get only 1 row returned. If you had multiple rows in result set you would need to loop through all of them
two ways
first is as people described
$max = "SELECT MAX(Id) as max_id FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
$row = mysqli_fetch_assoc($max1);
$max_id=$row['max_id'];
echo $max_id;
second is ordering and limiting
$max_id = 0;
$max = "SELECT id FROM trialtabel2 order by id desc limit 0,1";
$max1 = mysqli_query($dblink, $max);
while($row = mysqli_fetch_assoc($max1)){
$max_id=$row['id'];
}
echo $max_id;
In Your code you missing the fetch statement. you need to fetch from the resultset. see above what you are missing.
Try using this..,
$max = "SELECT MAX(Id) as maxId FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
$row = mysqli_fetch_assoc($max1);
echo $row['maxId'];
Hope this helps..
$max = "SELECT Id FROM trialtabel2 order by id desc limit 1";
$max1 = mysqli_query($dblink, $max);
$result = mysqli_fetch_assoc($max1);
pre($result);

Multiple page results with sql and php

I'm having trouble with the following code from a tutorial, it seems very simple but there must be something I'm missing. There is nothing at all where my numbered page menu should be, can anyone see why?
if (isset($_GET["page"])) { // get page number for query
$page = $_GET["page"];
}
else {
$page = 1; // no page number? set it
};
$start_from = ($page-1) * 20;
$query = "SELECT * FROM posts";
$query.= " WHERE isstart = 'y' AND iscomplete = 'n' ORDER BY date DESC LIMIT $start_from, 20";
$start_from, 20"; // use LIMIT (and options) to make sure only 20 are displayed
$result = mysql_query($query);
$query_count = "SELECT COUNT(post_ID) FROM posts WHERE isstart = 'y'";
$count_result = mysql_query($query_count);
$count_results = mysql_fetch_row($count_result);
$total_posts = $count_results[0];
$total_pages = ceil($total_posts / 20); // get total pages needed for page menu
for ($i=1; $i<=$total_pages; $i++) { // set the page numbers
$pagelink = "Page: <a href='index_test.php?page=".$i."'>".$i."</a>"; // make the page menu
};
$top_body_text = '<p align="left">'.$pagelink.'</p>';
Currently my statement echo'ing $pagelink creates noting.
First thing, there is a error on this line
$start_from, 20";
It should be
$start_from = 20;
and lastly, you need to echo '$pagelink' inside the for loop in order to see each pages number listed out. Example below:
if (isset($_GET["page"]))
{ // get page number for query
$page = $_GET["page"];
}
else {
$page = 1; // no page number? set it
};
$start_f = 20; // use LIMIT (and options) to make sure only 20 are displayed
$start_from = ($page-1) * $start_f;
$query = "SELECT * FROM posts";
$query.= " WHERE isstart = 'y' AND iscomplete = 'n' ORDER BY date DESC LIMIT $start_from, 20";
$result = mysql_query($query);
$query_count = "SELECT COUNT(post_ID) FROM posts WHERE isstart = 'y'";
$count_result = mysql_query($query_count);
$count_results = mysql_fetch_row($count_result);
$total_posts = $count_results[0];
$total_pages = ceil($total_posts / 20); // get total pages needed for page menu
for ($i=1; $i<=$total_pages; $i++)
{ // set the page numbers
echo $pagelink = "Page: <a href='index_test.php?page=".$i."'>".$i."</a>"; ///Echo here
};
$top_body_text = '<p align="left">'.$pagelink.'</p>';
Remove this line -- it's not doing anything:
$start_from, 20"; // use LIMIT (and options) to make sure only 20 are displayed
You'd already defined $start_from here:
$start_from = ($page-1) * 20;
Then check out your results and see if you are all set.

Order by and LIMIT both not working together in MySQL Query

i'm trying to Order by Desending and want to limit 30 in Query
PHP CODE
$page = $_POST['page'];
$cur_page = $page;
$page -= 1;
$per_page = 30;
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
$query_pag_data = "SELECT * from titles LIMIT $start, $per_page ORDER BY id DESC";
ERROR : MySql ErrorYou 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 id DESC' at line 1
PS: i'm using pagination... so limiting 30 result like this
correct syntax is:
SELECT * from titles
ORDER BY id DESC
LIMIT $start, $per_page
LIMIT at the end of the query.
change positions or LIMIT and ORDER BY, like:
$query_pag_data = "SELECT * from titles ORDER BY id DESC LIMIT $start, $per_page";
You have to put the limit at the end of the query for proper syntax:
$query_pag_data = "SELECT * from titles ORDER BY id DESC LIMIT $start, $per_page";
You need to put ORDER BY statement first before LIMIT
Correct syntax is as follows:
SELECT * FROM *table_name* WHERE *condition* ORBER BY *field_name* LIMIT *limit*;
LIMIT statement should always come at the end of the query.

MySQL displaying 1 result within while loop...however theirs actually 2 results?

I recently combined 2 queries into 1 (to optimize performance)...1 query for checking the count, and the other for the results, the count is to ensure their is actual results their before proceeding with the loop.
Heres the PHP code:
<?php
$query = 'SELECT id, title, COUNT(id) FROM submissions ORDER BY sub_time DESC LIMIT 50';
$result = mysql_query($query);
$count = mysql_result($result, 0, 2);
mysql_data_seek($result, 0); //mysql_result resets the internal pointer...
if ($count > 0) {
$i = 0;
while ($output = mysql_fetch_assoc($result)) {
++$i;
//etc..
}
}
?>
The problem is it now returns 1 result? - when theirs actually 2 results inside (as I've checked via PHPMyAdmin aswell as running the following code - see below), I've narrowed down the problem, its because the COUNT(id) has been combined with the intial results query; that its behaving like this.
Because if I do the following:
<?php
$query = 'SELECT id, title FROM submissions ORDER BY sub_time DESC LIMIT 50';
$result = mysql_query($query);
$i = 0;
while ($output = mysql_fetch_assoc($result)) {
++$i;
//etc..
}
?>
It returns 2 results...
So my question is how do i resolve this but achieve what I'm after?
I would recommend that you remove the COUNT(id) and use the mysql_num_rows() function to check how many rows were returned before trying to loop through them.
Your code could then look like this:
<?php
$query = 'SELECT id, title FROM submissions ORDER BY sub_time DESC LIMIT 50';
$result = mysql_query($query);
$count = mysql_num_rows($result);
if ($count > 0) {
$i = 0;
while ($output = mysql_fetch_assoc($result)) {
++$i;
//etc..
}
}
COUNT is an aggregate function that typically is used with the GROUP BY clause. I don't believe it is meaningful in the query as you used it.

Categories