MySQL INSERT INTO

MySQL Query statement "INSERT INTO" is used to insert new records in a table.

Insert Data Into a Database table

Syntax:
INSERT INTO table_name (column, column1, column2, column3, ...)
VALUES (value, value1, value2, value3 ...) 
Example:
<?php
// Database connection establishment
    $con=mysqli_connect("example.com","alex","qwerty","db_name");
    
// Check connection
    if (mysqli_connect_errno($con)) {
    echo "MySQL database connection failed: " . mysqli_connect_error();
    }

// Insert
    mysqli_query($con,"INSERT INTO contact (name,email,message)
        VALUES (Alex, '[email protected]', 'Sample message')")

?>  

Insert Data Into a Database using HTML form

The HTML Form:

<html>
<body>

<form action="submit.php" method="post">
  <table>
    <tr>
      <td>FirstName:</td>
      <td><input type="text" name="name" id="name" ></td>
    </tr>
    <tr>
      <td>Email:</td>
      <td><input type="text" name="email" id="email" ></td>
    </tr>
    <tr>
      <td>Message:</td>
      <td><textarea name="message" cols="40" rows="5" id="message"></textarea></td>
    </tr>
    <tr>
      <td><input name="submitBtn" type="submit" id="submitBtn"
value="Submit"></td>
    </tr>
  </table>
</form>

</body>
</html> 

In the above example, when a user clicks the submit button, form data will be sent to "submit.php".

"Submit.php" file connects to a database, and PHP $ _POST variable receives the value from the form.

Then, mysqli_query() function executes INSERT INTO statement, and a new record will be added to the "contact" table.

submit.php Page:

<?php
// Database connection establishment
    $con=mysqli_connect("example.com","alex","qwerty","db_name");
    
// Check connection
    if (mysqli_connect_errno($con)) {
        echo "MySQL database connection failed: " . mysqli_connect_error();
    }

//CHECKING SUBMIT BUTTON PRESS or NOT.
    if(isset($_POST["submitBtn"]) && $_POST["submitBtn"]!=""){ 
        $name=$_POST["name"];
        $email=$_POST["email"];
        $message=$_POST["message"];

//INSERT QUERY
    if(mysqli_query("INSERT INTO contact (name, email, message)
        VALUES ($name,$email,$message)")){
        echo "Record inserted successfully";
    }}
?>