问题
This is my first post here. I've searched in the site, but inforutunaly no matchs. Anyway, i want to know how to use named parameters on a class. so the pdo basic form is something like.
$query = $bdd->prepare('SELECT * FROM table WHERE login = :login AND pww = :pww');
$query->execute(array('login' => $login, 'pww' => $pww));
and i want to integrate this on a class regardless of the number of parameters. Currently, i have this code
http://pastebin.com/kKgSkaKt
and for parameters, i use somethings like ( which is wrong and vulnerable to injection )
require_once 'classes/Mysql.class.php';
$mysql = new Mysql();
$sql = 'SELECT * FROM articles WHERE id = '.$_GET['id'].' LIMIT 1';
$data = $mysql->select($sql);
And Thanks.
回答1:
So it's seems that i have figured it out, the trick was adding an optional parameter to the function, you use it whenver you need to work with prepared statements (named parameters). So the function is something like
public function selectAll($reqSelect, $param = null) {
$result = parent::prepare($reqSelect);
//Check whether the parameter was passed or not
if (is_null($param)) {
$result->execute();
$resultat = $result->fetchAll();
return $resultat;
}else{
//Binding the parameters
$result->execute($param);
$resultat = $result->fetchAll();
return $resultat;
}
$result->closeCursor();
}
and for applying it, it goes like
//First param, the SQL. Here we have named parameters, so we need them to get bind
$sql = 'SELECT * FROM articles WHERE publish = :number';
//Second param, the parameters that will get bind with the named ones
$param = array(':number' => 1);
$query = $mysql->selectAll($sql, $param);
foreach ($query as $row) {
extract($row);
echo $title . '<br />';
}
I don't know if this, is considered the best practice, secured or even correct. if i'm mistaken feel free to correct me.
来源:https://stackoverflow.com/questions/12709866/how-to-use-prepared-statements-named-parameters-on-a-php-class