I'm developing one API in php to display data on android app from my database using JSON.
In my app I want to display 20 records first, after display again 20 records once user scroll to top.
I'm requesting the last id of the record from app to show next 20 records from last id.
Here is my code
<?php
$last_movie = 0;
$genre = $_REQUEST['genre'];
$last_movie = $_REQUEST['lastid'];
require_once("connect.php");
$myArray = array();
if($last_movie == 0)
{
$result = $conn->query("SELECT * FROM my_movies WHERE genre = '$genre' ORDER BY year DESC LIMIT 20");
}
else
{
$result = $conn->query("SELECT * FROM my_movies WHERE genre = '$genre' ORDER BY year LIMIT ".$last_movie.",20");
}
if ($result) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
$result->close();
$conn->close();
?>
I'm getting values in some genres, but sometimes it show empty JSON.
I tried with this url
http://freemodedapk.com/bobmovies/by_genre.php?genre=Action
its working , whenever I try from last id
http://freemodedapk.com/bobmovies/by_genre.php?genre=Action&lastid=4714
It returns empty JSON. I have values in database.
But some genres working fine
http://freemodedapk.com/bobmovies/by_genre.php?genre=Drama
http://freemodedapk.com/bobmovies/by_genre.php?genre=Drama&lastid=865
I have total 4858 records in the database with all genres.
Anybody can help me to fix empty JSON problems in some of genres ?
Your main issue is in the wrong LIMIT usage: when you utilize 2 parameters for LIMIT keyword, the first one is for OFFSET value (not for IDs), the second one is to limit your result.
In short words: you should use LIMIT 0,20 to get the first 20 results, LIMIT 20,20 to show next 20 results and so on.
Also, your code is insecure - you have SQL injection. Try to not post direct urls on your sites with the source code which includes injection because some bad guys may drop your database or do some other harmful things.
Sample code is listed below (minor changes may be required):
<?php
require_once('connect.php');
$response = [];
$items_per_page = 20;
$page = (int) (($_REQUEST['page'] - 1) * $items_per_page);
$genre = $conn->escape_string($genre); # replace escape_string with proper method if necessary
$result = $conn->query("SELECT * FROM my_movies WHERE genre = '$genre' ORDER BY year DESC LIMIT $page,$items_per_page");
if ($result)
{
$response = $conn->fetch_all($result, MYSQLI_ASSOC); # replace fetch_all with proper method if necessary
}
echo json_encode($response);
$result->close();
$conn->close();
if you want to get last ID to ASC then use to
SELECT * FROM my_movies WHERE genre = '$genre' id<".$last_movie." ORDER BY year LIMIT 0,20
or if you want to get for pagination then your OFFSET value wrong,
you should be use LIMIT 0,20 to get the first 20 results, LIMIT 20,20 to next 20 , LIMIT 40,20
please check your SQL injection
look like Code
require_once('connect.php');
$result = [];
$limit = 20;
$pageNumber = (int) (($_REQUEST['pageNumber'] - 1) * $limit);
$genre = $conn->escape_string($genre);
$getDta = $conn->query("SELECT id,title,stream,trailer,directors,actors,quality,year,genre,length,translation,rating,description,poster FROM my_movies WHERE genre = '".$genre."' ORDER BY year DESC LIMIT $pageNumber,$limit");
if ($result)
$result =$conn->fetch_all($result, MYSQLI_ASSOC);
echo json_encode($result);
$result->close();
$conn->close();
Related
Maybe I am overthinking this, but I have narrowed my query to find a row down to 1 result that I need, and it will not display. Wondering if someone could tell me what I am doing wrong.
$result = mysqli_query($link, "SELECT pageid FROM article ORDER BY id DESC LIMIT 1");
$row = mysqli_use_result($result);
echo $row;
I have it selecting the last row and supplying me with the stored data from the pageid of the last row.
I had to adapt my code. I believe it was because I use mysql. However, this code will work if you use mysqli
$pageid = "SELECT pageid FROM articles ORDER BY id DESC LIMIT 1";
$resultpageid = $link->query($pageid);
if ($resultpageid->num_rows > 0) {
while ($row = $resultpageid->fetch_assoc()) {
$pagenumber = $row["pageid"];
}
} else {
echo "0 results";
}
mysqli doesn't have any function to get a single column from a single row. You need to use one of the fetch methods e.g. fetch_array(). You don't need any loop if you use LIMIT 1.
Just fetch a single row and get the column from the returned array:
$pageid = "SELECT pageid FROM articles ORDER BY id DESC LIMIT 1";
$resultpageid = $link->query($pageid);
$row = $resultpageid->fetch_assoc();
// or
$row = $resultpageid->fetch_array();
if ($row) {
echo $row["pageid"];
} else {
echo "No record found!";
}
I have a table photos with many photos in it and I need to select two at random:
In getnew.php
$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
$result2 = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
$row = $result->fetch_assoc();
$img1link = $row['link'];
// more stuff from $row
$row2 = $result2->fetch_assoc();
$img2link = $row2['link'];
// more stuff from $row2
However I need to prevent it from selecting the same photo twice (the selected photos must be different), i.e. $img1link should not = $img2link. I then need to retrieve the data using $.getJSON in another file, using an array at the end of getnew.php.
The array at the end of getnew.php:
echo json_encode(array('img1'=>$img1link,'img2'=>$img2link, ...(etc)... ));
How can I make sure the selected photos are different by the time the variable is stored in the array? I tried to create an if/else statement but didn't really understand what I was doing.
You can just execute once but get two instead so that you'll never pick the same row:
$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 2");
$row = $result->fetch_assoc();
$row2 = $result->fetch_assoc();
// invoke `->fetch` twice to get the first and second row
$img1link = $row['link'];
$img2link = $row2['link'];
Sidenote: Be careful of that ORDER BY rand() clause since it'll be slow on large data sets. You can use an alternative with #Bill Karwin's great answer
Run a single query -
$result1 = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 2");
while($row = $result->fetch_assoc()) {
$imglink[] = $row['link'];
}
You will get the links in $imglink[] array.
I have a php form that submits to MySQL, and a 2nd php form that uses the value stored via the first.
The highest value in the database for booth_member is currently 3. In the example below, = $booth_member should be equal to 4, but instead always returns 2.
$membersql = $mysqli->query("SELECT booth_member FROM users WHERE booth_number = '{$user['booth_number']}' ORDER BY booth_member DESC LIMIT 1");
$booth_member = $membersql + 1;
echo $booth_member;
If I try and echo $membersql, it simply returns 'array.'
mysqli::query returns a ressource object, that's why it's not working. Some code to fix it:
$membersql = $mysqli->query("SELECT booth_member FROM users WHERE booth_number = '{$user['booth_number']}' ORDER BY booth_member DESC LIMIT 1");
if($membersql->num_rows < 1)
{ /* error handling goes here */ }
else
{
$res_array = $membersql->fetch_assoc(); // save result as array
$booth_member = $res_array["booth_member"] + 1;
echo $booth_member;
}
Be sure to escape $user['booth_number'] before to prevent sql injection.
For more info, check the mysqli::query documentation :)
You require a bunch of try/catch code around this for a production system, but to test:
$result = $mysqli->query("SELECT booth_member FROM users WHERE booth_number = '{$user['booth_number']}' ORDER BY booth_member DESC LIMIT 1");
$booth_member = $result->fetch_object('booth_member');
++$booth_member;
echo $booth_member;
That's because it's an array. I believe you are trying to do:
$booth_member = $membersql['booth_member'] + 1;
Suppose I have code like that
$teachersql = mysql_query("SELECT * FROM `teacher` WHERE status = '2' ORDER BY name") or die(mysql_error());
while($teachers = mysql_fetch_array($teachersql))
{
echo "results";
}
But I have 100 results. I want only first 10 result in output. How? Please anybody help me now.
$teachersql = mysql_query("SELECT * FROM teacher
WHERE status = '2'
ORDER BY name
LIMIT 10")
The mandatory warning:
mysql_* is deprecated, use mysqli_* or PDO.
If you need 10 result in result set then you can make your code as below using limit.
$teachersql = mysql_query("SELECT * FROM `teacher` WHERE status = '2' ORDER BY name limit 10") or die(mysql_error());
or
if you want to fetch all rows and display only 10 result using while loop then you can use counter as below.
$cnt=0;
while($teachers = mysql_fetch_array($teachersql))
{
$cnt++;
echo "results";
if($cnt==10)
break;
}
Try:
SELECT * FROM teacher WHERE status = '2' ORDER BY name limit 10
How do I echo random id numbers from mysql database without repeating numbers?
this is my sample code:
$query = mysql_query("SELECT * FROM store");
$number=mysql_num_rows($query);
for ($count=1; $count<= $number ; $count++)
{
$id = mysql_query ("SELECT id FROM store ORDER BY RAND() LIMIT $number");
$id = mysql_fetch_assoc($id);
$id = $id['id'];
echo $id;
}
It will echo six random numbers but have instances like "1 1 3 2 4 5" where 1 is echoed twice instead of once. thanks in advance
Just order your results by rand and limit their number, your id has to be unique :
SELECT * FROM store ORDER BY RAND() LIMIT 0,6
The Problem is, that you do a SELECT inside of the loop, instead of selecting once and loop over the result.
$query = mysql_query("SELECT * FROM store");
$number=mysql_num_rows($query);
$result = mysql_query ("SELECT id FROM store ORDER BY RAND() LIMIT $number");
while ($row = mysql_fetch_assoc($result)) {
echo $row["id"];
}
BTW: SELECT * to get the number of recordsets is ugly, use SELECT count(id)instead
If you're coming out of php you're probably better off (faster, easier, no locking issues) to randomize your numbers there. And SQL queries inside loops is an antipattern.