从一组变量传递到多个php数据库表

gdrx4gfi  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(379)

我有一个html表单中的变量,该表单当前正在发布到数据库表中的一个表中。
我想在同一个函数中同时将这些相同的变量发布到其他表中。这可能吗?下面是我当前的php函数,它正在成功地发布到一个表中

<?php
    $var1 = $_POST['var1'];
    $var2 = $_POST['var2'];
    $var3 = $_POST['var3'];

    // Database connection
    $conn = new mysqli('localhost','user','password','database');
    if($conn->connect_error){
        echo "$conn->connect_error";
        die("Connection Failed : ". $conn->connect_error);
    } else {
        $stmt = $conn->prepare("insert into table1(var1, var2, var3) values(?, ?, ?)");
        $stmt->bind_param("sss", $var1, $var2, $var3);   
        $execval = $stmt->execute();
        echo $execval;
        $stmt->close();
        $conn->close();
    }
?>

我想把下面的变量发布到同一个数据库中的多个表中,所以我认为下面的方法不起作用-

<?php
    $var1 = $_POST['var1'];
    $var2 = $_POST['var2'];
    $var3 = $_POST['var3'];

    // Database connection
    $conn = new mysqli('localhost','user','password','database');
    if($conn->connect_error){
        echo "$conn->connect_error";
        die("Connection Failed : ". $conn->connect_error);
    } else {
        $stmt = $conn->prepare("insert into table1(var1, var2, var3) values(?, ?, ?)");
        $stmt->bind_param("sss", $var1, $var2, $var3);
        $stmt = $conn->prepare("insert into table2(var1) values(?)");
        $stmt->bind_param("s", $var1);
        $stmt = $conn->prepare("insert into table3(var2, var3) values(?, ?)");
        $stmt->bind_param("ss", $var2, $var3); 
        $execval = $stmt->execute();
        echo $execval;
        $stmt->close();
        $conn->close();
    }
?>
du7egjpx

du7egjpx1#

尝试调用$stmt->execute();每次调用$stmt->bind_param()之后;
看看这个在同一个调用中执行多个查询的已解决问题。pdo对多个查询的支持(pdo\ U mysql、pdo\ U mysqlnd)

mjqavswn

mjqavswn2#

是的,这是可能的。你可以做你现在正在做的,但是你需要打电话 execute() 方法。除此之外,将其 Package 到事务中也是一个好主意。事务有助于确保所有或无操作都成功。如果其中一个失败了,其他的就不会被执行。
您的固定代码应该如下所示:

<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];

// Database connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // switches error reporting on
$conn = new mysqli('localhost','user','password','database');
$conn->set_charset('utf8mb4'); // always set the charset

// Start transaction
$conn->begin_transaction();

$stmt = $conn->prepare("insert into table1(var1, var2, var3) values(?, ?, ?)");
$stmt->bind_param("sss", $var1, $var2, $var3);
$stmt->execute();

$stmt = $conn->prepare("insert into table2(var1) values(?)");
$stmt->bind_param("s", $var1);
$stmt->execute();

$stmt = $conn->prepare("insert into table3(var2, var3) values(?, ?)");
$stmt->bind_param("ss", $var2, $var3); 
$stmt->execute();

// End transaction
$conn->commit();

相关问题