MySQL Prepared Statements

坚强是说给别人听的谎言 提交于 2019-11-26 08:36:03

问题


I was just wondering if there was a way I could use some form of prepared statements in MySQL so I wouldn\'t have to escape all my inputs and I wouldn\'t have to switch all of my files from MySQL to MySQLi. I really don\'t trust the escaping functions, so if there is any alternatives that work in regular MySQL, it would be great.


回答1:


Use PDO (PHP Data Objects) to connect to your MySQL database. This method will make sure that all database input will always be treated as text strings and you will never have to do any manual escaping.

This combined with proper use of html_entities() to display data from your database is a solid and good way to protect your page from injection. I always use PDO to handle all my database connections in my projects.

Create database object (and in this case enforce a certain character encoding):

try {
    $db = new PDO("mysql:host=[hostname];dbname=[database]",'[username]','[password]');
    $db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8");
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    $db->exec('SET NAMES utf8');
} catch (PDOException $e) {
    echo $e->getMessage();
}

Then use it like so:

$id = 1;
$q = $db->prepare('SELECT * FROM Table WHERE id = ?');
$q->execute(array($id));
$row = $q->fetch();
echo $row['Column_1'];

or

$q = $db->prepare('UPDATE Table SET Column_1 = ?, Column_2 = ? WHERE id = ?');
$q->execute(array('Value for Column_1','Value for Column_2',$id));

and with wildcards:

$search = 'John';
$q = $db->prepare('SELECT * FROM Table WHERE Column_1 LIKE ?');
$q->execute(array('%'.$search.'%'));
$num = $q->rowCount();
if ($num > 0) {
  while ($row = $q->fetch()) {
    echo $row['Column_1'];
  }
} else {
  echo "No hits!";
}

Read more:

How can I prevent SQL injection in PHP?

When *not* to use prepared statements?

how safe are PDO prepared statements

http://php.net/manual/en/book.pdo.php




回答2:


If you don't want to deal with escaping your input, you can always pattern match it as it comes in then dispatch your prewritten statements. This is really only going to be worth the effort if you have relatively few possible statements to execute.



来源:https://stackoverflow.com/questions/6379433/mysql-prepared-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!