php - How to properly convert an array to sql string -
this question has answer here:
- passing array query using clause 16 answers
say i've got this:
$term_query = "and t.slug in ('" . $term_slugs . "') ";
where $term_slugs
id array this:
array('foto', 'video');
if simple implode(), won't work because cannot 'photo, video'. should foreach cycle build "'photo','video'". can't think way... unelegant. there other smarter way?
you use:
$term_query = "and t.slug in ('" . implode("','",$term_slugs) . "') ";
however prepared statements nicer:
$term_query = "and t.slug in ('" . implode(",",array_fill(0,count($term_slugs),"?") . ") "
now can bind parameters:
pdo binding
$stmt = $pdoobject->prepare($query); //query full query contains parametrised $term_query foreach ($term_slugs $index => &$slug) { $stmt->bindparam($index+1,$slug); //+1 because pdo parameters index starting 1 }
mysqli binding
$stmt = mysqli_prepare($query); //query full query contains parametrised $term_query $refarray = [ $stmt, array_fill(0,$term_slugs),"s") ]; //first 2 parameters bind param foreach ($term_slugs $index => &$slug) { $refarray[] = &$slug; //mysqli_bind_param needs references } call_user_func_array('mysqli_bind_param',$refarray);
Comments
Post a Comment