Question

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?

Was it helpful?

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.

OTHER TIPS

If the column id of your table log is a primary key, you get an error because PKs can't be NULL.

And your query is:

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

Use backticks for column and table names,not quotes.Assuming auto increment id.Also quote you POST names.

INSERT INTO people (`name`, `mother`, `address`, `city`) 
VALUES ('$_POST['name']', '$_POST['mother']', '', '$_POST'[address']', '$_POST['city']')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top