以单一形式更新联合搜索中的两个表

时间:2017-01-05 09:21:33

标签: php mysql

我有两个具有相同列名的表。我需要以单一形式进行搜索和更新,这是两个表格。

这是我的代码表单搜索和获取数据(看起来像工作):

if(isset($_POST['Search'])) {
    $NoMohon = $mysqli->real_escape_string($_POST['Nomor']);

    //query database
    $resultSet = $mysqli->query("SELECT * FROM table1 WHERE Nomor = '$Nomor' union SELECT * FROM table2 WHERE Nomor = '$Nomor'");

    if($resultSet->num_rows > 0) {
        while($rows = $resultSet->fetch_assoc()) {
            $Nomor = $rows['Nomor'];
            $Name = $rows['Name'];
            $Age = $rows['Age'];
        }
    } else {
        $output = "Data Null!";
    }
}

这里是我更新表的代码:

if(isset($_POST['Save'])) {
    $Nomor = $mysqli->real_escape_string($_POST['Nomor']);

    //query database
    $resultSet = $mysqli->query("SELECT * FROM table1 WHERE Nomor = '$Nomor' union SELECT * FROM table2 WHERE Nomor = '$Nomor'");

    $Name = strtoupper($_POST['Name']);
    $Age = strtoupper($_POST['Age']);

    //NEED WORKING CODE HERE
    $sql = $mysqli->query("UPDATE table1 SET Name ='{$Name}', Age ='{$Age}' where Nomor='$Nomor' union UPDATE table2 SET Name ='{$Name}', Age ='{$Age}' where Nomor='$Nomor'");
    header('Location: sukses.php');
}

如果搜索结果是table2中的值,那么我只想在table2中更新值。如果搜索结果是table1中的值,那么我只想在table1中更新值。

table1
+-------+-------------+---------+
| Nomor |   Name      |   Age   |
+-------+-------------+---------+ 
|  a1   | Supar       | 25      |
|  a2   | Rambo       | 23      |
+-------+-------------+---------+

table2
+-------+-------------+---------+
| Nomor |   Name      |   Age   |
+-------+-------------+---------+ 
|  b1   | Boneng      | 28      |
|  b2   | Dennyius    | 32      |
+-------+-------------+---------+

以上代码更新无效。所以请在这里帮助我。任何帮助,将不胜感激。感谢

1 个答案:

答案 0 :(得分:0)

您可以使用affected_rows属性,如下所示:

$mysqli->query("UPDATE table2 SET Name ='{$Name}', Age ='{$Age}' WHERE Nomor = '$Nomor'");
if (!$mysqli->affected_rows) { // no changes were made
  $mysqli->query("UPDATE table1 SET Name ='{$Name}', Age ='{$Age}' WHERE Nomor = '$Nomor'");
}

Documentation