gpt4 book ai didi

php - 从 $_get 绑定(bind) PDO mysql 参数不起作用

转载 作者:行者123 更新时间:2023-12-02 05:29:35 26 4
gpt4 key购买 nike

// url: http://localhost/asdf/?sort=credits


if(isset($_GET['sort'])){
$sort = $_GET['sort'];
}

$statement = $db->prepare("SELECT * FROM myTable ORDER BY :sort");
$statement->bindParam(':sort', $sort, PDO::PARAM_STR, 8);

var_dump($statement);
//object(PDOStatement)[2] public 'queryString' => string 'SELECT * FROM table1 ORDER BY :sort' (length=36)

$statement->execute();

我正在尝试从获取参数中获取排序选项,有人可以帮我吗?

更新正如@Uchiha Madara 所建议的,我创建了一些预定义的排序字符串

if(isset($_GET['sort'])){
switch ($_GET['sort']){
case 'val1':
$sortName = 'val1';
break;
case 'val2':
$sortName = 'val2';
break;

default:
$sortName = false;
break;
}
}

if($sortname != false){
// then prepare query
$statement = $db->prepare("SELECT * FROM table1 ORDER BY ?");
$statement->execute(array($sortName));
}

但仍然是相同的结果,排序选择被忽略

最后更新!

$sort = 'val1';

$orderList = array(
'val1',
'val2'
);

// then prepare query
$statement = $db->prepare("SELECT * FROM myTable ORDER BY $sort");
$statement->execute();

感谢@Madara Uchiha 和@Ray!

最佳答案

参见马德拉的 answer .

您不能绑定(bind)列。使用有效列的白名单数组进行排序(比较 $_GET 值)并将其代入查询:

$valid_cols = array('name', 'age');
$sort = 'default_sort_field';
if(isset($_GET['sort']) && in_array($_GET['sort'], $valid_cols)){
$sort = $_GET['sort'];
}

$statement = $db->prepare("SELECT * FROM myTable ORDER BY $sort");

关于php - 从 $_get 绑定(bind) PDO mysql 参数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12585144/

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