开发者

How to pass in N number of parameters into a prepared SQL statement in PHP?

I'm trying to pass in an unknown number of parameters (from 1-10) using an array to prepare my SQL statement for execution 开发者_开发知识库in PHP.

function executeStatement ($myArray) {

    //for example, $myArray = ("one", "two", "three")

    $qry = "SELECT * FROM table WHERE FieldA LIKE ".$myArray[0]." OR FieldA LIKE ".$myArray[1]." OR FieldA LIKE ".$myArray[2].";

    $result = mysql_query($qry) or die("Query failed with error: ".mysql_error());
}

Whats an efficient way to pass in N number of parameters using the array?


Not really sure how to do it with a prepared statement, but if I am understanding the questions correctly the below should work

$queryStr = "SELECT * FROM `table` WHERE ";
foreach($myArray as $single){
    $queryStr .= "$addStr`FieldA` LIKE '".mysql_real_escape_string($single)."'"; //Note the mysql_real_escape_string, this should help guard against sql injection
    $addStr = ' OR ';
}
$query = mysql_query($queryStr) or die(mysql_error());

Additionally, I would recommend using = instead of LIKE unless you are going to use wildcards


A prepared statement means one where the values are correctly escaped to protect the database from attack.

That is not what you have, you really need to escape the values yourself, perhaps you are doing this elsewhere, but I cannot see it.

To answer your question, try something like this:

function executeStatement ($myArray) {

    //for example, $myArray = array("one", "two", "three")

$qry = "SELECT * FROM table WHERE ";

foreach( $myArray as $arr ){

$flds[] = "FIELDA = '$arr' ";

}

$qry .= join(" OR " , $flds );
echo $qry;
}

If your values are not escaped elsewhere then do this:

$flds[] = "FIELDA = '". mysql_real_escape_string($arr) ."' ";

Notice you also used LIKE without quoting what was a string, and you had no wildcard character as used in LIKE so I tested for a match.

LIKE would look more like this:

$flds[] = "FIELDA LIKE '%". mysql_real_escape_string($arr) ."' ";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜