在一个mysql查询中更新两个表

时间:2015-07-04 05:26:46

标签: mysql

我在AJAX调用结束时有一个很好的一点点php / mysql工作,它会更新一个表。我现在需要更改此更新,以便帖子的PART更新一个表,另一个部分更新另一个表。我不清楚如何正确地做到这一点。这是我迄今为止所做的工作的代码:

if(isset($_POST['p2From'])) {
    $userInput = $_POST['p2From'];
    if(trim($userInput) == "") { $userInput = NULL; }
    try {
        $stmt = $conn->prepare("UPDATE $database.app_$applicationKey SET `p2From` = :userinput, `lastModified` = :time WHERE `appID` = :appid");
        $stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 8);
        $stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
        $stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
        $stmt->execute();
    } catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
}

我想要做的是有效地实现这一点:

if(isset($_POST['p2From'])) {
    $userInput = $_POST['p2From'];
    if(trim($userInput) == "") { $userInput = NULL; }
    try {
        $stmt = $conn->prepare("UPDATE $database.app_AIGtabs SET `p2From` = :userinput WHERE `appID` = :appid");
        $stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 8);
        $stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
        $stmt->execute();
    } catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
}

if(isset($_POST['p2From'])) {
    $userInput = $_POST['p2From'];
    if(trim($userInput) == "") { $userInput = NULL; }
    try {
        $stmt = $conn->prepare("UPDATE $database.app_$applicationKey SET `lastModified` = :time WHERE `appID` = :appid");
        $stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
        $stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
        $stmt->execute();
    } catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
}

然而,我想在一个更新查询中完成所有这一切,而不是两个。我确信这是可能的,但我不清楚如何在一个mysql查询中执行此操作。有人能告诉我如何实现这个目标吗?

1 个答案:

答案 0 :(得分:0)

使用多表更新语法:https://dev.mysql.com/doc/refman/5.6/en/update.html

if(isset($_POST['p2From'])) {
    $userInput = $_POST['p2From'];
    if(trim($userInput) == "") { $userInput = NULL; }
    try {
        $stmt = $conn->prepare("
            UPDATE $database.app_$applicationKey
            JOIN $database.app_AIGtabs on $database.app_$applicationKey.`appID` = $database.app_AIGtabs.`appID`
            SET `lastModified` = :time, `p2From` = :userinput
            WHERE $database.app_$applicationKey.`appID` = :appid;");
        $stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 8);
        $stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
        $stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
        $stmt->execute();
    } catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
}