如何在php类上使用准备好的语句(命名参数) [英] How to use prepared statements (named parameters) on a php Class

查看:31
本文介绍了如何在php类上使用准备好的语句(命名参数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在这里的第一篇文章.我已经在该网站中进行搜索,但可能没有匹配项.无论如何,我想知道如何在类上使用命名参数.所以pdo的基本形式是类似的.

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);

谢谢.

推荐答案

因此,看来我已经弄清楚了,诀窍是在函数中添加了一个可选参数,在需要使用准备好的语句时就可以使用它(命名参数).所以功能就像

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();
        }

并应用它,就像

//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.

这篇关于如何在php类上使用准备好的语句(命名参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆