如何将我的 SQL 语句更改为准备好的(和安全的)语句?

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

基本上我想保护自己免受 SQL 注射。我曾尝试在线搜索和观看视频,但无法准确理解我必须更改的内容,因为据我所知,每个人的做法都有点不同。感谢您的帮助!

?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();
?>

您必须首先使用 new mysqli() 而不是 mysqli_connect() 以避免在下一个 php 版本中出现任何错误

    <?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';
            }

   ?>

然后像这样做:

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