mysql 预备列,MySQL预备语句

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.

解决方案

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:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值