如何使用数组更新MySQL查询

时间:2019-03-23 13:41:03

标签: php mysql arrays

我是php新手。我有这个数组,我想更新我的表。

我的表格包含1到36列。

$test数组,包含键作为我的表列名称ie([0][2][4])和值作为我的表数据ie(1221 ),我想更新表格行。

$test=  Array
(
    [0] => 1
    [2] => 22
    [4] => 1
    [5] => 0.25
    [6] => 0.25
    [8] => 1.25
    [9] => 0.25
    [11] => 1
    [29] => 0.25
    [30] => 0.25
    [32] => 0.25
    [33] => 0.25
);

2 个答案:

答案 0 :(得分:0)

欢迎来到PHP-MySQL世界! ;)

我在数据库中的列名称只有数字的问题,但是此示例运行:

airports/ ^carriers/(?P<a_code>[A-Z]{3})/(?P<c_code>[A-Z0-9]{2})/$ [name='details']

答案 1 :(得分:-1)

使用此代码查询简单的SQL语句

    <?php
$test=  Array
(
    0 => 1,
    2 => 22,
    4 => 1,
    5 => 0.25,
    6 => 0.25,
    8 => 1.25,
    9 => 0.25,
    11 => 1,
    29 => 0.25,
    30 => 0.25,
    32 => 0.25,
    33 => 0.25
);
$query = 'update table_name set ';
$counter = 0;
foreach ($test as $columns => $value) {
  $query .= "{$columns} = {$value}";
  $counter++;
  if($counter!=count($test))
  $query.=', ';
}
$query .=' where some_column = some_value';
echo $query;
 ?>

对于准备好的语句,您可以执行以下操作

    <?php
$test=  Array
(
    0 => 1,
    2 => 22,
    4 => 1,
    5 => 0.25,
    6 => 0.25,
    8 => 1.25,
    9 => 0.25,
    11 => 1,
    29 => 0.25,
    30 => 0.25,
    32 => 0.25,
    33 => 0.25
);

$query = '$sql = UPDATE Applicant SET ';
$counter = 0;
foreach ($test as $columns => $value) {
  $query .= "{$columns} = ?";
  $counter++;
  if($counter!=count($test))
  $query.=', ';
}
$query .=' where some_column = ?';
echo $query;

$stmt = $mysqli->prepare($query);
$stmt->bind_param('iiiiiiiiiiii', $test[0],$test[2],$test[4],$test[5],$test[6],$test[8],$test[9],$test[11],$test[29],$test[30],$test[32],$test[33],$condition);
$stmt->execute();
 ?>

为了提高效率和安全性,建议您使用准备好的语句。谢谢