使用php数组更新MySQL表列

Sab*_*ish 0 php mysql arrays

我有以下数组$ weight,我想将这些值存储到mysql表中的weight列.

Array
(
    [0] => 12
    [1] => 14
    [2] => 16
    [3] => 9
    [4] => 7
)
Run Code Online (Sandbox Code Playgroud)

数据库表结构是,

+----------------------------+--------+------+
| Indicators                 | Weight | Rank |
+----------------------------+--------+------+
| Elevation                  |      0 |    0 |
| Distance from the sea      |      0 |    0 |
| Natural Coastal Protection |      0 |    0 |
| Water Bodies               |      0 |    0 |
| Precipitation              |      0 |    0 |
+----------------------------+--------+------+
Run Code Online (Sandbox Code Playgroud)

我期待结果为,

+----------------------------+--------+------+
| Indicators                 | Weight | Rank |
+----------------------------+--------+------+
| Elevation                  |     12 |    0 |
| Distance from the sea      |     14 |    0 |
| Natural Coastal Protection |     16 |    0 |
| Water Bodies               |      9 |    0 |
| Precipitation              |      7 |    0 |
+----------------------------+--------+------+
Run Code Online (Sandbox Code Playgroud)

尝试了以下查询,但似乎没有插入.

foreach($weight as $value)
    {
    $insert_weight="UPDATE geographic_main 
    SET Weight='$value' 
    WHERE Indicators=('Elevation','Distance from the sea',
    'Natural Coastal Protection','Water Bodies', 'Precipitation') ";
Run Code Online (Sandbox Code Playgroud)

我不确定我在WHERE部分是否正确.请建议.}

Cli*_*ive 6

您需要单独执行每个更新,此时看起来您正在进行混合并尝试将所有行更新为一次.你需要一些东西来识别你想要更新的记录,所以我推荐这个:

$weights = array(
  'Elevation' => 12,
  'Distance from the sea' => 14,
  'Natural Coastal Protection' => 16,
  // etc.
);

foreach ($weights as $key => $val) {
  $sql = "UPDATE geographic_main SET Weight = '$val' WHERE Indicators = '$key'";
  mysql_query($sql);
}
Run Code Online (Sandbox Code Playgroud)