You need to escape your string before putting it into the database.
Here is a basic example of how to do it in MySQLi
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Here is an example of PDO:
<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Dangerous string */
$string = 'Naughty \' string';
print "Unquoted string: $string\n";
print "Quoted string:" . $conn->quote($string) . "\n";
?>
You may want to consider using a prepared statement. There are several benefits to this including:
- Security - Helps prevent SQL injection
- Speed - You only are sending the values.
http://www.w3schools.com/php/php_mysql_prepared_statements.asp
Sources:
http://www.w3schools.com/php/func_mysqli_real_escape_string.asp
http://php.net/manual/en/mysqli.real-escape-string.php
http://php.net/manual/en/pdo.quote.php