简体   繁体   English

如何在条件下使用ARRAY查询mysql

[英]How can I query to mysql with ARRAY in condition

A have names of rows in array 有数组中的行名

$arr = array(fir, seco, third);

how can I query mysql like: 我怎样才能查询mysql:

$query = "SELECT * FROM $table where fir=0 and seco=0 and third=0";

but using array. 但是使用数组。

and

$query = "update $table SET fir='$ma', seco='$ma', third='$ma'";

but using array. 但是使用数组。

For search you can fire below query - 对于搜索,您可以在查询下面触发-

$str = implode(",", $arr);
$query = "SELECT * FROM $table where 0 IN ($str)";

But for update you have to use query what you have written. 但是对于更新,您必须使用查询来编写内容。

easy, 简单,

$arr = array(fir, seco, third);

for(int i = 0;i<arr.lenght;i++)
{
$query = $query + " and "  + arr[i] + "=" + $ma;
}

This is what I would do... 这就是我会做的...

$fir = $arr[0];
$seco = $arr[1];
$third = $arr[2];
$query = "UPDATE $table SET $fir = '$ma', $seco = '$ma', $third = '$ma'";

Not sure if there is a more optimal answer, but you could use a for loop to create the SQL statement: 不知道是否有更好的答案,但是可以使用for循环创建SQL语句:

<?php
$arr = array(fir, seco, third);

$query = "SELECT * FROM $table where ";
$count = count($arr);
for($i=0;$i<$count;$i++){
  $query .= ($i==$count-1) ? "$arr[$i]=0" : "$arr[$i]=0 and ";
}

echo $query;
?>

Echoes SELECT * FROM $table where fir=0 and seco=0 and third=0 . 回显SELECT * FROM $table where fir=0 and seco=0 and third=0 You can do the same with the UPDATE SQL statement. 您可以对UPDATE SQL语句执行相同的操作。

Update 更新

Also, you could implode the array, like in Suresh Kamrushi's answer, and use the following code: 同样,您可以像Suresh Kamrushi的答案那样使数组内爆,并使用以下代码:

<?php
    $arr = array(fir, seco, third);
    $str = implode(',',$arr);
    $query_one = "SELECT * FROM $table WHERE ($str) = (0,0,0)";
    echo $query_one;
?>

The UPDATE query would still need a for loop though, I think. 我认为UPDATE查询仍然需要for循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM