什么时候使用预备语句? [英] When to use prepared statements?

查看:100
本文介绍了什么时候使用预备语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个问题.

Spec:MySql数据库;服务器端语言PHP 5.3.10

Spec: MySql database; server side language PHP 5.3.10

1)什么时候应该使用准备好的语句?

1) When should one use prepared statements?

我正在构建一个有用户的webapp.我正在不断检索数据/将数据插入数据库.我目前没有使用准备好的语句,我想知道这是否是错误的处理方式?

I am building a webapp which has users. I am retrieving/inserting data into the database constantly. I am currently not using prepared statements and I was wondering if that was wrong way of doing things?

/**
     * Register a new user into the database.  Please make sure to
     * hash the password.
     * @param type $fName First name of the user - String value.
     * @param type $lName Last name of the user - String value.
     * @param type $email Email address of the user - String value.
     * @param type $hashedPassword - String value.
     * @return boolean true if sucessful or false if failed.
     */
    function registerUser($fName, $lName, $email, $hashedPassword)
    {
        //Establish a connection.
        $mysqli = new $mysqli($GLOBALS['dbServer'], $GLOBALS['dbUserName'], $GLOBALS['dbPassword'], $GLOBALS['dbName']);

        //Check if connection failed.
        if($mysqli->connect_error)
        {
            die('Connect Error (' .$mysqli->connect_errno . ') '
                    .$mysqli->connect_error);
        }

        //Insert data into the table and check if the attempt was sucessful.
        if($mysqli->query("INSERT INTO user_info(email, password, fName, lName) VALUE  ('$email', '$hashedPassword', '$fName', '$lName')"))
        {
            return true;
        }
        return false;            
    }

这是将值插入数据库并确保成功的正确方法吗?另外,我可以使用准备好的语句,但我想知道

Is this the proper way to insert a value into the database and make sure that it is successful? Alternatively, I can use prepared statements and I was wondering

2)我将如何使用准备好的语句?为什么要我(如果您建议我这样做)?

2) how would I go about using prepared statements? And why should I (if you suggest that I do)?

我预计每天大约有20,000次访问该网站.或者让我们假设那是多少...

I'm expecting roughly 20,000 visits to the website on daily bases. Or lets assume that's how many...

推荐答案

您应始终使用准备好的语句.这样可以防止SQL注入的任何机会(只要正确完成准备工作).我猜您还想知道何时可以使用常规查询来提高效率;硬件始终可以升级.请注意二阶SQL注入(示例).

You should always used prepared statements. That would prevent any chance of SQL injection (provided preparation done right). I'm guessing you also want to know when you can use regular queries for efficiency; hardware can always be upgraded. Watch out for second order SQL injection (example).

这篇关于什么时候使用预备语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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