HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Inserting users using PDO prepared statements

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
statementspreparedusinginsertinguserspdo

Problem

I made a small script to update fields in a database. I'm using PDO to connect to MySQL. All the business logic of PHP is in the top half of the file, and the form is at the bottom.

Here is the full code. If it's a POST request, it opens the PDO connection and inserts the values from the form.

prepare($sql);

        $statement->execute(array(
            "firstname" => $_POST['firstname'],
            "lastname"  => $_POST['lastname'],
            "email"     => $_POST['email'],
            "age"       => $_POST['age'],
            "location"  => $_POST['location']
        ));

    }

    catch(PDOException $error) 
    {
        echo $sql . "" . $error->getMessage();
    }
}
?>

    
    
    

    
    Update Users

    
        Add a user

            
                First Name
                
                Last Name
                
                Email Address
                
                Age
                
                Location
                
                
            
    


I know I can sanitize HTML input by doing something like:

function escape($html)
{
    return htmlspecialchars($html, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
}

// example use
escape($_POST['firstname']);


I'm wondering how necessary it is when I'm using a prepared statement. I'm still a bit confused about sanitization and filtering, and when it's necessary. I know it's necessary when printing data out to HTML, but not sure how much when receiving input to PDO.

Please forgive any and all ignorance. I'm writing this from scratch and doing my best to teach myself PHP without frameworks.

Solution

Do not escape SQL query parameters when using PDO. PDO will do the right thing. If you call unnecessary escaping functions "just in case", then you end up mangling the data. That's how you get junk like "this & that" appearing in some broken web pages.

When would you want to escape text using htmlspecialchars()? When outputting text to be embedded in HTML. For example,

">


If you didn't call htmlspecialchars() on $_POST['firstname'], then a malicious user could break the page by inputting a name that contained double-quotes.

Code Snippets

<input type="text" name="firstname" id="firstname" value="<?php echo escape($_POST['firstname']); ?>">

Context

StackExchange Code Review Q#163020, answer score: 2

Revisions (0)

No revisions yet.