Dynamically creating OR conditions by passing an array to a query in MySQL PHP

前端 未结 2 536
礼貌的吻别
礼貌的吻别 2021-01-23 16:23

I am trying to create OR condition dynamically using an array. Given an array, of course names $courses = array(\'Eng, \'Deu\', \'Bio\', \'Chemi\') I want to have a

2条回答
  •  走了就别回头了
    2021-01-23 16:58

    The IN clause will be easier to use than ORs. If you are using PDO you can take advantage of its execute binding and build the placeholders dynamically then just pass your array to it.

    $courses = array('Eng', 'Deu', 'Bio', 'Chemi');
    $placeholders = rtrim(str_repeat('?, ', count($courses)), ', ');
    $query = "select * from table WHERE class = 'EFG' AND course in ({$placeholders})";
    $stmt = $pdo->prepare($query);
    $stmt->execute($courses);
    

    Demo: https://3v4l.org/jcFSv (PDO bit non functional)

提交回复
热议问题