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

报告相同问题?

悬赏问题

  • ¥15 MATLAB代码补全插值
  • ¥15 Typegoose 中如何使用 arrayFilters 筛选并更新深度嵌套的子文档数组信息
  • ¥15 前后端分离的学习疑问?
  • ¥15 stata实证代码答疑
  • ¥50 husky+jaco2实现在gazebo与rviz中联合仿真
  • ¥15 dpabi预处理报错:Error using y_ExtractROISignal (line 251)
  • ¥15 在虚拟机中配置flume,无法将slave1节点的文件采集到master节点中
  • ¥15 husky+kinova jaco2 仿真
  • ¥15 zigbee终端设备入网失败
  • ¥15 金融监管系统怎么对7+4机构进行监管的