无法在foreach中运行多个UPDATE查询 - PHP

时间:2022-10-18 21:47:45

I have a array.

我有一个阵列。

$arr = 
Array
(
    [] => save
    [1] => 
    [2] => y786
    [5] => m987
    [23] =>
    [3] => g666
)

And i have written an UPDATE query inside foreach.

我在foreach中编写了一个UPDATE查询。

foreach($arr AS  $key => $value)
{
  if(!empty($key) && !empty($value)) //to chk empty key(for save) and to chk empty values
  {
    $sql = "UPDATE tablename SET code='$value' WHERE id='$key'";
    //execute query
  } 
}

So my update query is running only ONE time. It will check for 'non-empty' key and 'non-empty' value.

所以我的更新查询只运行一次。它将检查“非空”键和“非空”值。

In my above array only first pair. i,e [2] => y786 will be executed. How do i run my update queries for all 'non-empty' keys and 'non-empty' values.

在我上面的数组中只有第一对。 i,e [2] => y786将被执行。如何为所有“非空”键和“非空”值运行更新查询。

EDIT - Basically i need to run my UPDATE query neglecting my first index and neglecting my all empty values. In my above array i need to have 3 UPDATE queries for the keys 2,5,3 at a time.

编辑 - 基本上我需要运行我的UPDATE查询忽略我的第一个索引并忽略我的所有空值。在我上面的数组中,我需要一次对密钥2,5,3进行3次UPDATE查询。

1 个解决方案

#1


try this :

试试这个 :

    $arr = 
Array
(
    '' => 'save',
    1 => '',
    2 => 'y786',
    5 => 'm987',
    23 =>'',
    3 => 'g666'
);

foreach($arr AS  $key => $value)
{
  if(!empty($key) && !empty($value)) //to chk empty key(for save) and to chk empty values
  {
    $sql = "UPDATE tablename SET code='$value' WHERE id='$key'";
    //execute query
    echo $sql.'<br/>';
  } 
}

#1


try this :

试试这个 :

    $arr = 
Array
(
    '' => 'save',
    1 => '',
    2 => 'y786',
    5 => 'm987',
    23 =>'',
    3 => 'g666'
);

foreach($arr AS  $key => $value)
{
  if(!empty($key) && !empty($value)) //to chk empty key(for save) and to chk empty values
  {
    $sql = "UPDATE tablename SET code='$value' WHERE id='$key'";
    //execute query
    echo $sql.'<br/>';
  } 
}