简体   繁体   中英

PHP, SQL limit query by php variable

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.

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

Remove '' use only $sqlshowvalue :-

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

for integer value no need of ''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM