Search code examples
phpmysqlmysqliprepared-statementweb-traffic

When to use prepared statements?


I have few question.

Spec: MySql database; server side language PHP 5.3.10

1) When should one use prepared statements?

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) how would I go about using prepared statements? And why should I (if you suggest that I do)?

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


Solution

  • 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).