gpt4 book ai didi

PHP mysql 数据未从最后一个 id 检索

转载 作者:行者123 更新时间:2023-11-29 16:36:14 25 4
gpt4 key购买 nike

我正在 PHP 中开发一个 API,以使用 JSON 从我的数据库显示 Android 应用程序上的数据。

在我的应用程序中,我想先显示 20 条记录,然后在用户滚动到顶部后再次显示 20 条记录。我正在向应用请求记录的最后一个 ID,以显示最后一个 ID 中的接下来 20 条记录。

这是我的代码

<?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();



?>

我在某些类型中获取值,但有时它显示空 JSON。我尝试使用这个网址 http://freemodedapk.com/bobmovies/by_genre.php?genre=Action

每当我从最后一个 ID 开始尝试时,它都可以工作 http://freemodedapk.com/bobmovies/by_genre.php?genre=Action&lastid=4714

它返回空 JSON。我在数据库中有值。

<小时/>

但有些类型效果很好 http://freemodedapk.com/bobmovies/by_genre.php?genre=Drama http://freemodedapk.com/bobmovies/by_genre.php?genre=Drama&lastid=865

数据库中共有 4858 条记录,涵盖所有流派。

有人可以帮我解决某些类型中的空 JSON 问题吗?

最佳答案

您的主要问题在于错误的 LIMIT 使用:当您使用 LIMIT 关键字的 2 个参数时,第一个参数用于 OFFSET 值(不适用于 ID),第二个参数用于限制您的结果。

简而言之:您应该使用 LIMIT 0,20 来获取前 20 个结果,使用 LIMIT 20,20 来显示接下来的 20 个结果,依此类推。

此外,您的代码不安全 - 您存在 SQL 注入(inject)。尽量不要在您的网站上发布包含注入(inject)的源代码的直接网址,因为一些坏人可能会删除您的数据库或做一些其他有害的事情。

下面列出了示例代码(可能需要进行细微更改):

<?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();

关于PHP mysql 数据未从最后一个 id 检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53587221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com