Search code examples
phpmysqlloggingsystemmultiple-tables

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


I have a form, which will insert records into table people, and also, I want to register a system log by inserting into another table called log.

This is the form:

<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>

And the page inserting.php will be like this:

<?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; . "."
    }

?>

What is wrong? How to do it?


Solution

    1. Don't use raw $_POST in you queries! Never!

    2. Use prepared statements to insert user data.

    3. Always check for query result and read from mysqli_error() to check what is wrong.

    In this case you're not putting $_POST[name] in ' so it'll lead to syntax error. Also in first query you are using ' instead of ` to wrap column names.