Reputation: 245
For some reason addslashes is NOT adding slashes when inserting data into database. I thought I was using this right, but clearly not... When I submit data that has single or double quotes, it is just sending the exact string right in. Any ideas on how to make this work?
<?php
//include db connect
include ("db_con.php");
//start session
session_start();
//set variable names
$username = $_SESSION['username'];
$entry = addslashes($_POST['entry']);
$uri = $_SERVER['HTTP_REFERER'];
//send chat
$query = mysqli_query($con, "INSERT INTO chat (username, entry) VALUES
('".$username."', '".$entry."')");
if ($query) {
header('Location: '. $uri);
} else {
echo 'Chat entry failed for an unknown reason - Please go back and try again';
}
?>
Upvotes: 0
Views: 2158
Reputation: 1732
Using addslashes()
when dealing with databases is very bad practice. Since you're using PHP's mysqli extension, you should escape your data with mysqli_real_escape_string()
. The PHP manual page for addslashes()
explains why.
Upvotes: 1
Reputation: 1489
addslashes()
is for escaping the string. If you got code:
$lastname = "O'Bama";
$query = "SELECT name FROM users WHERE lastname='$lastname'";
The query will produce an error because Bama
will be treated as SQL statement. To prevent this you can use addslashes()
so
echo addslashes($lastname); // returns O\'Bama
Now you can execute your query without any errors because your database will see value as "O'Bama".
Upvotes: 2