我该怎样"消毒"我的数据输入是为了对抗SQL注入?

时间:2015-04-18 15:16:24

标签: php sql code-injection

我一直致力于一个关于网站创意的项目,但我注意到我可以在我的网站上实际执行SQL注入。这不好,因为如果可以,那么任何人都可以。什么是为PHP站点清理数据输入的“最佳”方法?

<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "users";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$fname = $_POST['fname'];
$lname = $_POST['lname'];
$pnum = $_POST['pnum'];
$cc = $_POST['cc'];
$username = $_POST['username'];
$password = $_POST['password'];

$sql = "INSERT INTO Users (fname, lname, cc, pnum, username, password) VALUES ('$fname', '$lname', '$cc', '$pnum', '$username', '$password')";
$result = $conn->multi_query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    header('Location: registered.html');
}

$conn->close();
?>

1 个答案:

答案 0 :(得分:0)

使用旨在防止注射的预准备语句。

http://php.net/manual/en/pdo.prepared-statements.php