Saturday, 15 June 2013

php - match array against database -



php - match array against database -

i have array(61) contain possible user names , want validate each 1 of them against database entry. using next code:

foreach(profilename("dev","db") $k => $val){ $db->query("select profile_name eb_user_account profile_name = '$val'"); if($db->numrows() == 0){ echo $val ." [match found @ key: {$k}]"; break; } }

profilename("dev","db") function holds array. code works nice , smooth , break match doesn't occur. curious if there faster , improve way perform task. please suggest me.

with thanks

you're looking combination of mysql's in operator, , phpimplode() function:

$query = sprintf( 'select profile_name eb_user_account profile_name in (%s)', implode(',', profilename("dev","db")) );

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

$stmt = $dbh->prepare('select * table col in (?)'); $rs = $stmt->execute(array(implode(',', $myarray)));

will fail. number of parameters in in statement must match number of placeholders. eg:

$stmt = $dbh->prepare('select * table col in (?,?,?)'); $rs = $stmt->execute(array(1,2,3));

on sec thought...

$myarray = profilename("dev","db"); $placeholders = array_fill(0, count($myarray), '?'); $query = sprintf( 'select profile_name eb_user_account profile_name in (%s)', implode(',', $placeholders); ); $stmt = $dbh->prepare($query); $rs = $stmt->execute($myarray);

should have parameterized correctly.

php arrays

No comments:

Post a Comment