note 112642 added to pdo.prepared-statements

From: Date: Mon, 08 Jul 2013 11:59:43 +0000
Subject: note 112642 added to pdo.prepared-statements
Groups: php.notes 
Request: Send a blank email to php-notes+get-195502@lists.php.net to get a copy of this message
Replace the query() by a prepare()/execute() for having one line like a sprintf() old query() renamed for remember to secure. <?php class MyPDO extends PDO{ const DB_HOST='localhost'; const DB_PORT='3306'; const DB_NAME='test'; const DB_USER='root'; const DB_PASS=''; public function __construct($options=null){ parent::__construct('mysql:host='.MyPDO::DB_HOST.';port='.MyPDO::DB_PORT.';dbname='.MyPDO::DB_NAME, MyPDO::DB_USER, MyPDO::DB_PASS,$options); } public function query($query){ //secured query with prepare and execute $args = func_get_args(); array_shift($args); //first element is not an argument but the query itself, should removed $reponse = parent::prepare($query); $reponse->execute($args); return $reponse; } public function insecureQuery($query){ //you can use the old query at your risk ;) and should use secure quote() function with it return parent::query($query); } } $db = new MyPDO(); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); $t1 = isset($_GET["t1"])?$_GET["t1"]:1; // need to be securised for injonction $t2 = isset($_GET["t2"])?$_GET["t2"]:2; // need to be securised for injonction $t3 = isset($_GET["t3"])?$_GET["t3"]:3; // need to be securised for injonction $ret = $db->query("SELECT * FROM table_test WHERE t1=? AND t2=? AND t3=?",$t1,$t2,$t3); //$ret = $db->insecureQuery("SELECT * FROM table_test WHERE t1=".$db->quote($t1)); while ($o = $ret->fetch()) { echo $o->nom.PHP_EOL; } ?> ---- Server IP: 69.147.83.199 Probable Submitter: 82.226.97.114 ---- Manual Page -- http://php.net/manual/en/pdo.prepared-statements.php Edit -- https://master.php.net/note/edit/112642 Del: integrated -- https://master.php.net/note/delete/112642/integrated Del: useless -- https://master.php.net/note/delete/112642/useless Del: bad code -- https://master.php.net/note/delete/112642/bad+code Del: spam -- https://master.php.net/note/delete/112642/spam Del: non-english -- https://master.php.net/note/delete/112642/non-english Del: in docs -- https://master.php.net/note/delete/112642/in+docs Del: other reasons-- https://master.php.net/note/delete/112642 Reject -- https://master.php.net/note/reject/112642 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#195502) next »