使用php数组更新MySQL表列


Updating a MySQL table column with php array

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

Array
(
    [0] => 12
    [1] => 14
    [2] => 16
    [3] => 9
    [4] => 7
)

数据库表结构为,

+----------------------------+--------+------+
| Indicators                 | Weight | Rank |
+----------------------------+--------+------+
| Elevation                  |      0 |    0 |
| Distance from the sea      |      0 |    0 |
| Natural Coastal Protection |      0 |    0 |
| Water Bodies               |      0 |    0 |
| Precipitation              |      0 |    0 |
+----------------------------+--------+------+

我期待的结果是,

+----------------------------+--------+------+
| Indicators                 | Weight | Rank |
+----------------------------+--------+------+
| Elevation                  |     12 |    0 |
| Distance from the sea      |     14 |    0 |
| Natural Coastal Protection |     16 |    0 |
| Water Bodies               |      9 |    0 |
| Precipitation              |      7 |    0 |
+----------------------------+--------+------+

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

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') ";

我不确定我在哪里部分是否正确。请建议。}

您需要单独执行每个更新,目前看起来您正在进行混合,并试图一次更新所有行。你需要一些东西来识别你要更新的记录,所以我建议这样做:

$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);
}

您可以添加"index"或"id"列到表或使用以下代码

$index = 0;
$q = mysql_query("SELECT Indicators FROM geographic_main");
while(list($indicator) = @mysql_fetch_row($q)) {
   mysql_query("UPDATE geographic_main SET Weight='".$weights[$index++]."' WHERE Indicators='$indicator'");
}

但这不是正确的方式

你真的需要一个id列在你的表…因为…我如何识别我当前所在的行?因此,如果你不想使用id列,你可以创建数组索引,或者字典/关联数组。

$idx = array(
     'Elevation'                      => 0
    ,'Distance from the sea'          => 1
    ,'Natural Coastal Protection'     => 2
    ,'Water Bodies'                   => 3
    , 'Precipitation'                 => 4
);
foreach($idx as $name => $i) {
     mysql_query("UPDATE geographic_main SET Weight = '".$weights[$i]."' WHERE Indicators = '".$name."'";
}

,但无论如何,最好使用id,因为您可以更接近db引擎。

希望这对你有帮助。祝你过得愉快

费利佩。