如何使用 PHP 将数组元素处理到 MySQL 中? [英] How to process array element into MySQL with PHP?

查看:32
本文介绍了如何使用 PHP 将数组元素处理到 MySQL 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个数组的元素,然后像这样使用 PHP 将它放到 MySQL 查询中:

I want to get elements of an array, and put it to MySQL query using PHP like this:

$ArrayOne = {3, 5, 8, 2};
$sql = SELECT * from myTable WHERE id1='3' and id2='5' and id3='8' and id4='2';

我是这样做的,但失败了:

I do it like this, but it's failed:

for ($i=0; $i<count($ArrayOne); $i++) {
  $element.$i = $ArrayOne[$i];
}
  $sql = ("SELECT * from myTable WHERE id1=". $element.$i ." and id2=". $element.$i ." and id3=". $element.$i ." and id4=". $element.$i .");

我认为 $element.$i 具有相同的值,但我不知道如何获取 Array 元素的不同值.如果我这样做,那也是错误的.

I think the $element.$i has the same value, but I don't know how to get the different value of Array element. And if I do like this, it's also wrong.

for ($i=0; $i<count($ArrayOne); $i++) {
  $element.$i = $ArrayOne[$i];    
  $sql = ("SELECT * from myTable WHERE id1=". $element.$i ." and id2=". $element.$i ." and id3=". $element.$i ." and id4=". $element.$i .");
}

任何机构都可以给出解决方案吗?

Can any body give the solution?

推荐答案

你的代码有几个错误

第一个是:

$ArrayOne = {3, 5, 8, 2};

应该是:

$ArrayOne = array(3, 5, 8, 2);

第二个错误,你的 $sql 变量没有用引号括起来应该是 $sql="your query";

2nd mistake, your $sql variable doesnt has enclosed between quotes should be $sql="your query";

如果你的数组有固定长度,你就不需要使用循环:

if your array has a fix length you dont have need to use a loop:

$ArrayOne = array(3, 5, 8, 2);

 $sql =  "SELECT     * 
     from       myTable 
     WHERE      id1='$ArrayOne[0]'
     and        id2='$ArrayOne[1]'
     and        id3='$ArrayOne[2]'
     and        id4='$ArrayOne[3]'";

对于可变长度的数组,您可以使用@Nightmare 的答案

For an array of variable length you can use the @Nightmare's answer

附注:

阅读SQL 注入

你应该学习 PDO,如果你开始学习 php,那就用正确的方法来

You should learn PDO, if you are starting to learn php, do it the right way

手册

这篇关于如何使用 PHP 将数组元素处理到 MySQL 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆