Often, after filling out the form, we need to send our data to the MySQL database immediately. In this example, we will consider the option of sending data object-oriented method and the usual functional method.
In any case, we need to create a test HTML form to begin with:
<html> <head> <title>Test form</title> <meta charset="utf-8" /> </head> <body> <form action="add-user.php" method="post"> <input type="text" name="username" placeholder="Add name" /></p> <input type="number" name="age" placeholder="age" /></p> <input type="submit" value="Add"> </form> </body> </html>
Axction of our form leads to the page add-user.php.
Let’s create this file and add the following code to it:
OOP PHP example:
if (isset($_POST["username"]) && isset($_POST["age"])) { // Connecting to the database $conn = new mysqli("localhost", "root", "password", "testdb"); // Checking connection errors if ($conn->connect_error) { die("Error: " . $conn->connect_error); } // Escaping special characters in a string to prevent SQL injections $namefield = $conn->real_escape_string($_POST["username"]); $agefield = $conn->real_escape_string($_POST["age"]); // Preparing an SQL Query $sql = "INSERT INTO Users (name, age) VALUES (?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param("si", $namefield, $agefield); $stmt->execute(); // Adding data to the database and displaying errors if ($stmt->affected_rows > 0) { echo "User added"; } else { echo "Error: " . $stmt->error; } // Closing a connection $stmt->close(); $conn->close(); }
Function example:
if (isset($_POST["username"]) && isset($_POST["age"])) { $conn = mysqli_connect("localhost", "root", "password", "testdb"); if (!$conn) { die("Error: " . mysqli_connect_error()); } $namefield = mysqli_real_escape_string($conn, $_POST["username"]); $agefield = mysqli_real_escape_string($conn, $_POST["age"]); $stmt = mysqli_prepare($conn, "INSERT INTO Users (name, age) VALUES (?, ?)"); mysqli_stmt_bind_param($stmt, "si", $namefield, $agefield); if (mysqli_stmt_execute($stmt)) { echo "User added"; } else { echo "Error: " . mysqli_error($conn); } mysqli_stmt_close($stmt); mysqli_close($conn); }
mysqli_real_escape_string() – allows you to protect against SQL injections