多个sql语句PHP

时间:2016-12-05 21:29:59

标签: php sql

我正在尝试对mySQL数据库执行多个更新。它似乎只执行最后一个sql语句。

<?php
$AppName1 = "////MilAppName";
$AppName2 = "////MilAuditors";
$AppNewName = "Iabc";
$AppNewName1 = "Iabcd";
$conn = mysqli_connect("*****", "****", "****", "****");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "UPDATE AppName SET AppTitle = '$AppNewName' WHERE Plant = '$AppName1'";
$sql = "UPDATE Auditors SET Auditor1 = '$AppNewName1' WHERE Plant = '$AppName2'";


if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

2 个答案:

答案 0 :(得分:0)

您只运行1 mysqli_query($conn, $sql),当您运行它时,您的$sql变量只保留第二个查询。

每次mysqli_query()声明后,您需要运行$sql

或者您可以将包含2个查询的2个变量命名为:

$sql1 = "UPDATE AppName SET AppTitle = '$AppNewName' WHERE Plant = '$AppName1'";
$sql2 = "UPDATE Auditors SET Auditor1 = '$AppNewName1' WHERE Plant = '$AppName2'";


if (mysqli_query($conn, $sql1) && mysqli_query($conn, $sql2)) {
  echo "Record updated successfully";
} else {
  echo "Error updating record: " . mysqli_error($conn);
}

答案 1 :(得分:0)

您正在做的是替换SQL语句,您需要声明2个var名称或在执行SQL后替换该语句:

$sql = "UPDATE AppName SET AppTitle = '$AppNewName' WHERE Plant = '$AppName1'";

if (mysqli_query($conn, $sql)) {
    $sql = "UPDATE Auditors SET Auditor1 = '$AppNewName1' WHERE Plant = '$AppName2'";
    if (mysqli_query($conn, $sql)) {
        echo "Record updated successfully";
    }else {
        echo "Error updating record: " . mysqli_error($conn);
    }
} else {
    echo "Error updating record: " . mysqli_error($conn);
}


$sql1 = "UPDATE AppName SET AppTitle = '$AppNewName' WHERE Plant = '$AppName1'";       
$sql2 = "UPDATE Auditors SET Auditor1 = '$AppNewName1' WHERE Plant = '$AppName2'";

if (mysqli_query($conn, $sql1)) {
    if (mysqli_query($conn, $sql2)) {
        echo "Record updated successfully";
    }else {
        echo "Error updating record: " . mysqli_error($conn);
    }
} else {
    echo "Error updating record: " . mysqli_error($conn);
}