简体   繁体   English

用每页的顺序构建mysqli查询以显示

[英]Building a mysqli query with order by and per page to show

The page display all results, now I want to filter results and how many results per page. 该页面显示所有结果,现在我要过滤结果以及每页多少个结果。 To do this the visitor use a simple html GET form to select the filter. 为此,访问者使用简单的html GET表单来选择过滤器。

Now I get the GET form and try to filter the results 现在,我获取了GET表单,并尝试过滤结果

<?php
$order_by = mysqli_real_escape_string($database,$_GET['order_by']);
$order = if(empty($order_by)){echo 'manufacturer';}else{echo '$order_by';
?>

OK now we get the filter and try to get results from MySQL like this 好的,现在我们得到过滤器,并尝试从MySQL这样获得结果

$set_order=mysqli_query($database,"SELECT * FROM `products` order by `$order` ASC");}

But I get error in the line: 但我在一行中得到错误:

   $order = if(empty($order_by)){echo 'manufacturer';}else{echo '$order_by';

Cannot find a way to do this ... Any idea? 无法找到一种方法来做...有什么想法吗?

using single quotes around a variable will not work - but why not assign the variable and then echo it back? 在变量周围使用单引号将不起作用-但是为什么不分配变量然后将其回显呢?

$order = empty($order_by) ? 'manufacturer' : $order_by;
echo $order;

if however this is to be used in the sql query you do not need to echo it. 但是,如果要在sql查询中使用它,则无需回显它。

After a short 8r break for sleep you have an answer but I'll post this here too. 在短暂的8r睡眠后,您会得到一个答案,但我也会在此处发布。

$order = empty($order_by) ? 'manufacturer' : $order_by;
$sql="select * from `products` order by `{$order}` asc;";

$set_order=mysqli_query( $database, $sql );
if( $set_order ){
    /* process recordset */
}

尝试这个:

if(empty($order_by)){$order = 'manufacturer';}else{$order = $order_by;} 

First, set a default value for order by. 首先,为order by设置默认值。

$order = 'manufacturer';

Next, if the user has provided something else, replace the default value with that. 接下来,如果用户提供了其他内容,则用该默认值替换。

if (!empty($_GET['order_by'])) {
    $order = mysqli_real_escape_string($database, $_GET['order_by']);
}

Then you can use whatever it ends up being in your query. 然后,您可以使用最终在查询中使用的任何内容。

$set_order = mysqli_query($database, "SELECT * FROM `products` order by `$order` ASC");

It is definitely good that you're using mysqli_real_escape_string here, but I would recommend checking the user input against a list of acceptable column names to mitigate the SQL injection risk. 在这里使用mysqli_real_escape_string绝对好,但是我建议您对照可接受的列名列表检查用户输入,以减轻SQL注入的风险。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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