dongzhi8487 2012-09-25 14:28
浏览 29
已采纳

从$ _get绑定PDO mysql参数不起作用

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

Im trying to an ordering option from the get parameters, can anyone help me out?

update as suggest by @Uchiha Madara, i created some predifed ordering strings

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

but still same result, ordering choice is ignored

last update!

$sort = 'val1';

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

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

thank @Madara Uchiha and @Ray!

  • 写回答

2条回答 默认 最新

  • drau67562 2012-09-25 14:30
    关注

    Maybe because you named you variable $sort, but you're trying to bind $order?

    That's because you can't bind column names with prepared statements. They're only meant to be used with values.

    Instead, what you should do, is to have a set of predefined options, and sort by those. You shouldn't give the user a choice of directly ordering by a real column name.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元