Search code examples
phphtmlmysqlsecuritycode-injection

How can I change my SQL statements to be prepared (and secure) statements?


Basically I want to protect myself from SQL injections. I have tried searching online and watching videos but cannot understand exactly what I have to change because as far as I can tell, everyone does it a little bit differently. Any help is appreciated!

?php
// Create connection
$con = mysqli_connect("IPAddress","User","Password","DBName");
// Check connection
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
}

$sql = "INSERT INTO Email_Subs (email)
VALUES ('$_POST[email]')";

if ($con->query($sql) === TRUE) {
    echo "You have successfully subscribed!";
} else {
    echo "Error: " . $sql . "<br>" . $con->error;
}

$con->close();
?>

Solution

  • You must first use new mysqli() instead of mysqli_connect() to avoid any error in the next php versions

        <?php 
    
        /* CONNECTION */
        $database_connection = new StdClass();
    
        /** MySQL hostname */
        $database_connection->server = 'localhost';
    
        /** MySQL database username */
        $database_connection->username = 'root';
    
        /** MySQL database password */
        $database_connection->password = '';
    
         /** The name of the database */
         $database_connection->name = 'yourdatabasename';
    
         /* ESTABLISHING THE CONNECTION */
        $database = new mysqli($database_connection->server, $database_connection->username, $database_connection->password, $database_connection->name); 
    
                if($database->connect_error) {
    
                    echo 'connection failed';
                }
    
       ?>
    

    Then do smething like this :

    $stmt = $database->prepare("INSERT INTO Email_Subs (email) VALUES (?)"); 
    $stmt->bind_param("s", $_POST[email]);
    $stmt->execute();
    $stmt->close();
    $database->close();