简体   繁体   中英

match array against database

I have an array(61) which contain possible user names and i want to validate each one of them against database entry. i am using the following code:

foreach(profileName("Dev","Db") as $k => $val){
    $db->query("SELECT profile_name FROM eb_user_account WHERE profile_name = '$val'");
    if($db->numRows() == 0){
        echo $val ." [match found at key: {$k}]";
        break;
    }
}

profileName("Dev","Db") function holds the array. this code works nice and smooth and break exactly where match doesn't occur. i am just curious if there is a faster and better way to perform this task. please suggest me.

with thanks

您可以使用MySQL的IN()子句,例如

SELECT * FROM myTable WHERE profile_name IN ('foo', 'bar')

You're looking for a combination of mySQL's IN operator, and the PHP implode() function:

$query = sprintf(
    'SELECT profile_name FROM eb_user_account WHERE profile_name IN (%s)',
    implode(',', profileName("Dev","Db"))
);

It's worth noting that if you're using parameterized queries it is not possible to pass an list of arguments of arbitrary length. eg:

$stmt = $dbh->prepare('SELECT * FROM table WHERE col IN (?)');
$rs = $stmt->execute(array(implode(',', $myarray)));

Will fail. The number of parameters in the IN statement must match the number of placeholders. eg:

$stmt = $dbh->prepare('SELECT * FROM table WHERE col IN (?,?,?)');
$rs = $stmt->execute(array(1,2,3));

On second thought...

$myarray = profileName("Dev","Db");
$placeholders = array_fill(0, count($myarray), '?');
$query = sprintf(
    'SELECT profile_name FROM eb_user_account WHERE profile_name IN (%s)',
    implode(',', $placeholders);
);
$stmt = $dbh->prepare($query);
$rs = $stmt->execute($myarray);

Should have everything parameterized correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM