担心SQL注入。我的代码是否正确?

时间:2013-11-22 12:57:20

标签: php mysql sql sql-server pdo

我是SQL查询的新手,我一直在根据网站和本网站提供的信息进行学习,这些信息从2005年到今年发布的信息各不相同。我正在创建一个将数据插入MySql数据库的php应用程序。当我研究Sql注入时,网上有很多信息。我阅读了各种方法来实现它,例如使用mysql_real_escape_string,使用sqli或PDO准备语句和参数化查询等。我已经把我学到的东西放在一起,并使用sqli方法进行准备和参数化查询。在我在我的网站上发布它之前,我只是想确保我已经正确地完成它,如果这应该阻止SQL注入。我对此感到非常紧张,如果有人能够让我知道以下查询是否对我在我的实际网站上有安全性,那将会非常有用。我是新手,只需要重新保证:

我现在有以下代码:

//Connect to Database

$user_input_Name = $_POST['Name'];
$user_input_date = $_POST['date'];
$user_input_info = $_POST['info'];
$user_input_resume = $_POST['resume'];
$user_input_experience = $_POST['experience'];
$user_input_dateGraduated = $_POST['dateGraduated'];

//Preparing the query 
$stmt = $mysqli->prepare("INSERT INTO our_weekend_template (name, date, info, resume, experience, date_graduated) VALUES (?, ?, ?, ?, ?, ?)");

// Check that $stmt creation succeeded
// prepare() can fail because of syntax errors, missing privileges, ....
if ( false===$stmt ) {
  // and since all the following operations need a valid/ready statement object
  // it doesn't make sense to go on
  // you might want to use a more sophisticated mechanism than die()
  // but's it's only an example
  die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}

// "s" means the database expects a string
$rc = $stmt->bind_param("ssssss", $user_input_Name, $user_input_date, $user_input_info, $user_input_resume, $user_input_experience, $user_input_dateGraduated );

// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if ( false===$rc ) {
  // again execute() is useless if you can't bind the parameters. Bail out somehow.
  die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}

$stmt->execute();

// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if ( false===$rc ) {
  die('execute() failed: ' . htmlspecialchars($stmt->error));
}

$stmt->close();


//Disconnect from database 

我在这里做的是我使用prepare,bind_param和execute来处理查询,然后为它的每一步添加一个错误,如果它失败,那么它对调试很有用。

这些是我提到的将上述代码放在一起的页面:

How can I prevent SQL injection in PHP?

MySQLi prepared statements error reporting

http://www.wikihow.com/Prevent-SQL-Injection-in-PHP

是否可以,我可以安全地获取我的实际网站上的代码吗?我错过了什么吗?我是否需要改进任何内容以提高安全性?

1 个答案:

答案 0 :(得分:1)

准备好的语句暂停了SQL注入,所以是的,你做得对!您的错误处理也非常好:)

稍微偏离主题:

在PHP中,您不必明确地将值与false进行比较。 if语句中的所有内容都会自动解析为布尔值。所以非空对象返回true,而false显然返回... false。

if(!$stmt) die();

然而,你的代码绝对没有错。

相关问题