dongnianchou7047 2016-08-10 00:48 采纳率: 0%
浏览 34
已采纳

PHP PDO使用IN和WHERE运算符准备语句

I am new to PDO (coming from mysqli) and I have been searching for hours and cannot seem to figure out how to combine the WHERE and IN operators with PDO prepared statements.

Simple WHERE (Works Fine):

$value1 = 'val1';
$value2 = 'val2';
$stmt = $pdo->prepare('SELECT * FROM mytable WHERE val1 = ? AND val2 = ?');
$stmt->bindParam(1, $value1);
$stmt->bindParam(2, $value2);
$stmt->execute();

IN Statement (Works Fine)

$myArr = ['NY', 'PARIS', 'ROME'];
$q  = str_repeat('?,', count($myArr) - 1) . '?';
$sql = "SELECT * FROM myTable WHERE cities IN ($q)";
$stmt = $db->prepare($sql);
$stmt->execute($myArr);

Combining (Not Working):

$value1 = 'val1';
$myArr = ['NY', 'PARIS', 'ROME'];
$q  = str_repeat('?,', count($myArr) - 1) . '?';
$sql = "SELECT * FROM myTable WHERE column = ? AND cities IN ($q)";
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $value1);
$stmt->execute($myArr);

Thanks In Advance!

  • 写回答

1条回答 默认 最新

  • dtrotfd1012 2016-08-10 01:09
    关注

    I believe the reason this is not working is because you are using both

    $stmt->bindParam(1, $value1); $stmt->execute($myArr);

    To use an array and make it work do as follows:

    prepare($sql);

    execute($myArr);

    In $myArr you should include whatever columns = ? is supposed to be, you can add this to the beginning of the array using array_unshift() like this array_unshift($myArr, 'X'); http://php.net/manual/en/function.array-unshift.php

    After calling array_unshift() the variable $myArr will have the values as follows:

    [myArr] => Array
            (
                [0] => X
                [1] => NY
                [2] => PARIS
                [3] => ROME
            )
    

    Now you can call the PDO statements correctly:

    prepare($sql);
    execute($myArr);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 微信聊天记录备份到电脑提示成功了,但还是没同步到电脑微信
  • ¥15 python怎么在已有视频文件后添加新帧
  • ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,
  • ¥15 fluent里模拟降膜反应的UDF编写
  • ¥15 MYSQL 多表拼接link
  • ¥15 关于某款2.13寸墨水屏的问题
  • ¥15 obsidian的中文层级自动编号
  • ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网
  • ¥15 神经网络模型一直不能上GPU
  • ¥15 pyqt怎么把滑块和输入框相互绑定,求解决!