How to use prepared statements (named parameters) on a php Class

喜夏-厌秋 提交于 2021-02-19 05:34:38

问题


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

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