PHP:如何将数组值插入mysql语句

时间:2014-02-04 05:32:50

标签: php mysql arrays

我有这个数组并从网址获取它。这个数组是我需要传递给mysql的成员id。

$member_id = $_GET['member_id'];

这样的数组:Array ( [0] => 1269 [1] => 385 )

我怎样才能将这个数组转移到我的mysql 语句中,然后成为AND:

$answer_sql = mysql_query("SELECT tna_category. * , tna_question. *, tna_answer. * 
                        FROM tna_category, tna_question, tna_answer 
                        WHERE  tna_category.section_id = '$section_id1' 
                        AND tna_question.id = tna_answer.question_id AND tna_question.category_id = tna_category.id 
                        AND tna_answer.member_id = ['1269' , '385']
                        ORDER BY tna_answer.question_id");

我应该放括号吗?..

在此部分中: tna_answer.member_id =数组或$ member_id

4 个答案:

答案 0 :(得分:2)

正如其他人所说,你可以使用IN(),但你显然对SQL注入攻击持开放态度。你需要这样做:

$escaped_ids = array_map('mysql_real_escape_string', $member_ids);

或者,如果他们肯定是所有整数

$escaped_ids = array_map('intval', $member_ids);

然后,您可以编写如下查询:

$query = "SELECT tna_category. * , tna_question. *, tna_answer. * 
          FROM tna_category, tna_question, tna_answer 
          WHERE  tna_category.section_id = '" . mysql_real_escape_string($section_id1) . "' 
              AND tna_question.id = tna_answer.question_id 
              AND tna_question.category_id = tna_category.id 
              AND tna_answer.member_id IN (".implode(",", $escaped_ids).")
          ORDER BY tna_answer.question_id";

永远不要永远不要在您的查询中放入未转义的值。

此外,您不应再使用mysql_功能了。请考虑使用mysqli_功能。

答案 1 :(得分:1)

首先拆分数组值,得到否。数组值中的行,并使用for或foreach循环将值逐个传递到查询中。

答案 2 :(得分:1)

试试这个

$member_id = $_GET['member_id'];

如果您已经获得了逗号分隔值,那么在数据库查询中只需使用explode函数就不需要使用implode函数。

$member_id = explode(",", $member_id);  

然后

answer_sql = mysql_query("SELECT tna_category. * , tna_question. *, tna_answer. * 
                        FROM tna_category, tna_question, tna_answer 
                        WHERE  tna_category.section_id = '$section_id1' 
                        AND tna_question.id = tna_answer.question_id AND tna_question.category_id = tna_category.id 
                        AND tna_answer.member_id IN (".implode(",", $member_id).")
                        ORDER BY tna_answer.question_id");

explode函数创建数组,它取决于您使用逗号OR空格的explode值,然后implode意味着用逗号OR空格连接这些值。 有关详细信息explodeimplode

答案 3 :(得分:-1)

你可以像这样使用mysql的IN子句

$your_array = array("0"=>"1269", "1"=>"385");


 $in_text = implode(",", $your_array);

   $sql = "SELECT tna_category. * , tna_question. *, tna_answer. * 
        FROM tna_category, tna_question, tna_answer 
        WHERE  tna_category.section_id = '$section_id1' 
               AND tna_question.id = tna_answer.question_id 
               AND tna_question.category_id = tna_category.id  
               AND tna_answer.member_id IN ($in_text)
               ORDER BY tna_answer.question_id";