dongshi949737 2017-02-01 20:55
浏览 311
已采纳

ORDER BY FIELD(id,?)无法在PDO中工作

I am trying to execute a query that shows only articles inside this array $res. It contains article IDs

$res = Array ( [0] => 42 [1] => 41 );

$res1 = $res;
$res2 = $res;

$Search = $db->prepare("
    SELECT * FROM articles
    WHERE id IN :res1
    ORDER BY FIELD(id, :res2);
");

$Search->execute([
    ':res1' => $res1,
    ':res2' => $res2
]);

but it is returnig this error

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? ORDER BY FIELD(id, ?)' at line 2 in C:\xampp\htdocs\index.php:16 Stack trace: #0 C:\xampp\htdocs\index.php(16): PDO->prepare(' \t\t\tSELECT * F...')

  • 写回答

2条回答 默认 最新

  • douaoli5328 2017-02-01 22:09
    关注

    You're trying to pass an array as a parameter. That won't work. Also, IN takes a comma separated list inside parentheses, and that's not how to declare an array in PHP.

    $res = [42, 41];
    
    $params = array_merge($res, $res);
    // build a big list of question marks
    // for a two element array we get ?,?
    $placeholder = trim(str_repeat("?,", count($res)), ",");
    
    $Search = $db->prepare("
        SELECT * FROM articles
        WHERE id IN ($placeholder)
        ORDER BY FIELD(id, $placeholder);
    ");
    
    $Search->execute($params);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角