我是否正确使用PDO来阻止sql注入?

时间:2014-07-04 14:48:53

标签: php mysql security pdo sql-injection

我花了最后一天试图弄清楚如何将PDO合并到我的代码中以防止sql注入。这就是我想出的。但是,每当我从浏览器提交信息时,它都不会更新到我的表中,也不会显示任何错误消息。有些事情是错的,但我不确定是什么。我是积极的,语法不是问题因为我多次检查过。我知道我的数据库可以访问,所以我认为我使用PDO的方式存在问题。请帮帮我们。

PSBE_LOGIN包含访问我的数据库的所有信息

<?php
require_once 'PSBE_LOGIN.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);

if (!$db_server) die("Unable to connect to MySQL:" . mysql_error());

mysql_select_db($db_database, $db_server) 
or die("Unable to select database:" . mysql_error());

if (isset($_POST['title']) &&
isset($_POST['author']) &&
isset($_POST['isbn']))
//This checks to see if there is a value inputted into the form at the bottom
{
$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');
//This retrieves information from the user and assigns it to a variable

$stmt = $pdo->prepare('INSERT INTO classifieds(title, author, isbn)
        . VALUES(:title, :author, :isbn)');
$stmt->execute(array('title'=> $title, 'author'=> $author, 'isbn' => $isbn));
}

echo <<<_END
<form action="PSBE_POST_AD.php" method="post">
Title <input type="text" name="title" />
Author <input type="text" name="author" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</form>
_END;

?>

编辑:包含PDO API的代码更新。

<?php
require_once'connection.php';

$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);

if (isset($_POST['title']) &&
isset($_POST['author']) &&
isset($_POST['isbn']))
//This checks to see if there is a value inputted into the form at the bottom
{
$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');
//This retrieves information from the user and assigns it to a variable

$stmt = $pdo->prepare('INSERT INTO classifieds(title, author, isbn)
        . VALUES(:title, :author, :isbn)');
$stmt->execute(array('title'=> $title, 'author'=> $author, 'isbn' => $isbn));
}

echo <<<_END
<form action="PSBE_POST_AD.php" method="post">
Title <input type="text" name="title" />
Author <input type="text" name="author" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</form>
_END;

function get_post($var){
  return mysql_real_escape_string($_POST[$var]);
}

?>

2 个答案:

答案 0 :(得分:4)

摆脱两者

$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');

function get_post($var){
  return mysql_real_escape_string($_POST[$var]);
}

因为您使用的功能基于mysql_功能而且这两个API不会混用。

您不需要它,因为您已经在使用占位符。

替换为

$title = $_POST['title'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];

您还需要更改

$stmt = $pdo->prepare(...

$stmt = $db->prepare(...

给出您的PDO连接$db = new PDO(...

答案 1 :(得分:0)

正确使用它们。您需要connect using the PDO API(您使用mysql_ API进行连接)。否则,准备工作是正确的。