php - 如何使用占位符/准备好的语句将数据添加到mysql中的特定列

标签 php mysql security

我正在学习如何从教科书中进行编码,它给出了如何使用占位符将数据添加到表中的示例,但它没有显示如何仅将数据添加到特定列。这就是我想到的

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

$q = 'PREPARE statement FROM "INSERT INTO classifieds(title, author, isbn)'
        . 'VALUES(?,?,?)"';
mysql_query($q);

$q = 'SET @title = "$title",' .
     '@author = "$author",' .
     '@isbn = "$isbn",';
mysql_query($q);

$q = 'EXECUTE statement USING @title,@author,@isbn';
mysql_query($q);

$q = 'DEALLOCATE PREPARE statement';
mysql_query($q);
}

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"Post Classified" />
</form>
_END;
?>

但是,每当我将信息提交到浏览器中时,我都会检查它是否是通过 phpmyadmin 添加的,但事实并非如此。我正在制作一个分类网站,我需要最高的安全性,这就是我选择使用占位符的原因。我尝试在网上寻找使用许多不同语法的解决方案,但它们都不起作用。那么这段代码有什么问题呢?任何建议将不胜感激。

最佳答案

虽然mentioned textbook关于准备好的语句是“virtually bulletproof”的说法是正确的,但是在准备语句并手动设置参数时,正确传递参数值的问题仍然存在。

教科书上的示例仅使用静态值,这不是很有帮助。然而,您想出了一个解决方案,除了 mentioned syntax error 之外,该解决方案也可以工作,但以不安全的方式合并这些值,这使您仍然容易受到 SQL 注入(inject)的攻击。<​​/p>

这里的解决方案是使用 mysql_real_escape_string 作为字符串文字值:

$q = 'SET @title = "'.mysql_real_escape_string($title).'",' .
     '@author = "'.mysql_real_escape_string($author).'",' .
     '@isbn = "'.mysql_real_escape_string($isbn).'";';

但是,有些 MySQL API 支持 native 准备好的语句,您无需摆弄 mysql_real_escape_string

查看 How can I prevent SQL-injection in PHP? 中的示例。例如,使用 PDO,语句准备和执行将如下所示:

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

这也使用准备好的语句,但 PDO 负责正确的参数传递。

关于php - 如何使用占位符/准备好的语句将数据添加到mysql中的特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24565289/

相关文章:

javascript - Searchfuntion 在 Symfony2 中使用 ajax 调用

php - 如何确保从 MySQLi::multi_query 中捕获所有错误?

php - 在 PHP 7.0 中编码多维数组不起作用 (json_encode)

php - Mysql 表连接来自 2 个表的记录,但获取所有记录,甚至包含空字段的记录

php - HTML 表单不通过 PHP 处理器将数据发布到 MySQL 数据库

PHP 函数不将数据传递到 MySQL

mysql - MYSQL 中带时区的日期格式

javascript - 如何阻止非浏览器客户端提交请求?

php - 拒绝从浏览器访问公共(public) php 但允许应用程序使用

security - 找不到 catalina.sh