PHP, SQL limit query by php variable

自闭症网瘾萝莉.ら 提交于 2019-12-31 05:38:16

问题


PHP code defining variable sqlshowvalue

$sqlshowvalue = 5;
if(isset($_POST['showmore'])) {
     $sqlshowvalue += 5;
}

So I connect to my database and then when I run this SQL query below using the variable that I just defined above,

$result = mysqli_query($conn,"SELECT * FROM comments ORDER BY id DESC limit '$sqlshowvalue'");

So I am using mysqli as the method to connect to my DB and it gives me the following error:

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in ..

The reason it gives me this error is because something in my query is wrong and what it has to do is $sqlshowvalue, because if I replace sqlshowvalue with with just the number 5 (like shown below), it works fine:

$result = mysqli_query($conn,"SELECT * FROM comments ORDER BY id DESC limit 5");

So I am just wondering what I can do to make it so that the value for the limit is a PHP variable that I can be changed and the page updated.


回答1:


Have you tried making

$result = mysqli_query($conn,"SELECT * FROM comments ORDER BY id DESC limit '$sqlshowvalue'");

to

$result = mysqli_query($conn,"SELECT * FROM comments ORDER BY id DESC limit ".$sqlshowvalue);



回答2:


Remove '' use only $sqlshowvalue:-

$result = mysqli_query($conn,"SELECT * FROM comments 
ORDER BY id DESC limit $sqlshowvalue");

for integer value no need of ''



来源:https://stackoverflow.com/questions/33338496/php-sql-limit-query-by-php-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!