English 中文(简体)
如何在N号参数中将参数纳入PHP中准备的SQ表?
原标题:How to pass in N number of parameters into a prepared SQL statement in PHP?
  • 时间:2011-09-13 13:36:34
  •  标签:
  • php
  • mysql

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());
}

在使用阵列的N数参数中采用何种有效方法?

最佳回答

如果我正确理解下面的问题,那么如何用一份准备好的发言来做到这一点,那么,如果我理解这些问题,那么工作就应该正确。

$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());

此外,我建议使用=而不是LKE,除非你使用野心。

问题回答

编制的声明意味着这些数值被正确地越走以保护数据库免遭攻击。

这不是你所拥有的,你真的需要逃脱价值观,或许你在其他地方这样做,但我看不到。

回答你的问题,试图这样做:

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;
}

如果你们的价值观在其他地方得不到,那么:

$flds[] = “FIELDA =”. mysql_real_einski_string($arr) ;

通知你还使用LKE,但没有引证什么,你没有使用LKE所用的野心,因此我测试了配对。

扫盲与扫盲运动会更像:

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




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签