Search code examples
phpfat-free-framework

Is there a way of sanitize an array for an IN condition on PHP Fat Free Framework?


For example, if I want to sanitize a string, I use the following code

$db->exec("SELECT * FROM users WHERE email = :email", [':email' => 'john.smith@gmail.com']);

But if I want to use a IN condition the following code does not work

$db->exec("SELECT * FROM users WHERE email IN :emails", [':emails' => ['john.smith@gmail.com', 'juan.perez@gmail.com']]);

what is the proper way to do this? Thanks for your time


Solution

  • Unfortunately there's not easy way to do it, as the PDO class itself doesn't provide any mechanism for it.

    Here's how to do it:

    $emails = ['john.smith@gmail.com', 'juan.perez@gmail.com'];
    
    $sql = 'SELECT * FROM users WHERE email IN (' .
           implode(',', array_fill(0, count($emails), '?')) . ')';
    $i = 1;
    $args = [];
    foreach ($emails as $email)
      $args[$i++] = $email;
    
    $db->exec($sql, $args);
    

    UPDATE:

    Actually, I didn't see george007's answer, which is much more concise than mine. I didn't know that the framework automatically corrects any 0-indexed arguments array (PDO requires index to start at 1).

    So here's the most concise you can get:

    $emails = ['john.smith@gmail.com', 'juan.perez@gmail.com'];
    
    $sql = 'SELECT * FROM users WHERE email IN (?' . str_repeat(',?', count($emails)-1) . ')';
    
    $db->exec($sql, $emails);