Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Special Characters

What is the best way to allow all special character in you database and keeping it safe, and not being pron to a SQL injection?

2 Answers

If you are using MySQLi then you can use something that's called a prepared statement. e.g:

$stmt = $dbConnection->prepare('SELECT * FROM movies WHERE title = ?');
$stmt->bind_param('s', $title);

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something for each returned $row
}

Here you are a preparing a statement to get all columns from the table movies where the column title is equal to the php variable $title.

On the second row (bind_param) you are "replacing" or binding the question-mark (?) of the statement with that variable. The s means that the variable you are binding is a string.

Next, on the third row, you are executing that statement, and then store it in $result.

bind_param() will secure your database from first-level injections which is in most cases a sufficient measure.

Andrew Shook
Andrew Shook
31,709 Points

Just to add, PDO offers similar capibilities. Only difference is PDO's bind method is called bind and not bind_param.

Welby Obeng
Welby Obeng
20,340 Points

you can also use mysqli_real_escape_string() around the value before inserting it into the database