try {//Connect as appropriate as above$db->query('hi'); //Invalid query!}catch (PDOException $ex) {echo "An Error occured!"; //User friendly message/message you want to show to usersome_logging_function($ex->getMessage());}
function data_fun($db) {$stmt = $db->query("SELECT * FROM table");return $stmt->fetchAll(PDO::FETCH_ASSOC);}
//Then latertry {data_fun($db);}catch(PDOException $ex) {//Here you can handle error and show message/perform action you want.}
class person {public $name;public $add;function __construct($a,$b) {$this->name = $a;$this->add = $b;}
}$demo = new person('john','29 bla district');$stmt = $db->prepare("INSERT INTO table (name, add) value (:name, :add)");$stmt->execute((array)$demo);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);$pdo->query('SET NAMES GBK');$stmt = $pdo->prepare("SELECT * FROM test WHERE name = ? LIMIT 1");$stmt->execute(array(chr(0xbf) . chr(0x27) . " OR 1=1 /*"));
mysql> create table users(-> id int(2) primary key auto_increment,-> userid tinytext,-> pass tinytext);Query OK, 0 rows affected (0.05 sec)
mysql> insert into users values(null, 'Fluffeh', 'mypass');Query OK, 1 row affected (0.04 sec)
mysql> create user 'prepared'@'localhost' identified by 'example';Query OK, 0 rows affected (0.01 sec)
mysql> grant all privileges on prep.* to 'prepared'@'localhost' with grant option;Query OK, 0 rows affected (0.00 sec)
完成后,我们可以转到我们的PHP代码。
让我们假设以下脚本是网站管理员的验证过程(简化但如果您复制并将其用于测试,则可以使用):
<?php
if(!empty($_POST['user'])){$user=$_POST['user'];}else{$user='bob';}if(!empty($_POST['pass'])){$pass=$_POST['pass'];}else{$pass='bob';}
$database='prep';$link=mysql_connect('localhost', 'prepared', 'example');mysql_select_db($database) or die( "Unable to select database");
$sql="select id, userid, pass from users where userid='$user' and pass='$pass'";//echo $sql."<br><br>";$result=mysql_query($sql);$isAdmin=false;while ($row = mysql_fetch_assoc($result)) {echo "My id is ".$row['id']." and my username is ".$row['userid']." and lastly, my password is ".$row['pass']."<br>";$isAdmin=true;// We have correctly matched the Username and Password// Lets give this person full access}if($isAdmin){echo "The check passed. We have a verified admin!<br>";}else{echo "You could not be verified. Please try again...<br>";}mysql_close($link);
?>
<form name="exploited" method='post'>User: <input type='text' name='user'><br>Pass: <input type='text' name='pass'><br><input type='submit'></form>
<?php
if(!empty($_POST['user'])){$user=$_POST['user'];}else{$user='bob';}if(!empty($_POST['pass'])){$pass=$_POST['pass'];}else{$pass='bob';}$isAdmin=false;
$database='prep';$pdo=new PDO ('mysql:host=localhost;dbname=prep', 'prepared', 'example');$sql="select id, userid, pass from users where userid=:user and pass=:password";$myPDO = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));if($myPDO->execute(array(':user' => $user, ':password' => $pass))){while($row=$myPDO->fetch(PDO::FETCH_ASSOC)){echo "My id is ".$row['id']." and my username is ".$row['userid']." and lastly, my password is ".$row['pass']."<br>";$isAdmin=true;// We have correctly matched the Username and Password// Lets give this person full access}}
if($isAdmin){echo "The check passed. We have a verified admin!<br>";}else{echo "You could not be verified. Please try again...<br>";}
?>
<form name="exploited" method='post'>User: <input type='text' name='user'><br>Pass: <input type='text' name='pass'><br><input type='submit'></form>
include_once("pdo_mysql.php");
pdo_connect("localhost", "usrABC", "pw1234567");pdo_select_db("test");
$result = pdo_query("SELECT title, html FROM pages");
while ($row = pdo_fetch_assoc($result)) {print "$row[title] - $row[html]";}
Et voilà. Your code is using PDO. Now it's time to actually utilize it.
Bound parameters can be easy to use
You just need a less unwieldy API.
pdo_query() adds very facile support for bound parameters. Converting old code is straightforward:
Move your variables out of the SQL string.
Add them as comma delimited function parameters to pdo_query().
Place question marks ? as placeholders where the variables were before.
Get rid of ' single quotes that previously enclosed string values/variables.
The advantage becomes more obvious for lengthier code.
Often string variables aren't just interpolated into SQL, but concatenated with escaping calls in between.
pdo_query("SELECT id, links, html, title, user, date FROM articlesWHERE title='" . pdo_real_escape_string($title) . "' OR id='".pdo_real_escape_string($title) . "' AND user <> '" .pdo_real_escape_string($root) . "' ORDER BY date")
使用?占位符,您不必为此烦恼:
pdo_query("SELECT id, links, html, title, user, date FROM articlesWHERE title=? OR id=? AND user<>? ORDER BY date", $title, $id, $root)