如何插入到两个表中?其中之一是用于注册日志


How can I insert into two tables? One of them is for registering a log

我有一个表单,它将记录插入表people,而且,我想通过插入另一个名为log的表来注册系统日志

这是形式:

<form action="inserting.php" method="POST">
    
    <input type="text" name="name">
    <input type="text" name="mother">
    <input type="text" name="address">
    <input type="text" name="city">
    <input type="submit" name="submit" value="Insert">
</form>

页面inserting.php将是这样的:

<?php
    if(isset($_POST['submit'])){
        
        $insert = mysqli_query($con, "INSERT INTO people ('id', 'name', 'mother', 'address', 'city') VALUES (NULL, '$_POST[name]', '$_POST[mother]', '', '$_POST[address]', '$_POST[city]')");
        $log = mysqli_query($con, "INSERT INTO log (id, name, date, time) VALUES (NULL, $_POST[name], $date, $time)");
        echo $_POST['name'] . "was successfully inserted on" . $time . "of" . $date; . "."
    }
?>

怎么了?怎么办?

  1. 不要在查询中使用原始$_POST!从不!

  2. 使用预准备语句插入用户数据。

  3. 始终检查查询结果并从mysqli_error()读取以检查错误所在。

在这种情况下,您不会将$_POST[name]放入',因此会导致语法错误。同样在第一个查询中,您使用 ' 而不是 ' 来包装列名。

如果表日志的列 ID 是主键,则会收到错误,因为 PK 不能为 NULL。

您的查询是:

$log = mysqli_query($con, "INSERT INTO log (id, name, date, time) VALUES (NULL, $_POST[name], $date, $time)");

对列名和表名使用反引号,而不是引号。假设自动递增 ID。还要引用您的 POST 名称。

INSERT INTO people (`name`, `mother`, `address`, `city`) 
VALUES ('$_POST['name']', '$_POST['mother']', '', '$_POST'[address']', '$_POST['city']')
相关文章: