Adding HTML form data to the MySQL database. PHP OOP and fun... open

Adding HTML form data to the MySQL database. PHP OOP and functional examples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: PHP 5.6 +

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

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation