Reputation: 11
I've looked at other examples on here, but everyone else's syntax is different from what I have, so I have no clue where to put "mysql_real_escape_string". Here is my current code:
include("dbconnect.php");
mysql_select_db("scratch", $con);
$sql= "INSERT INTO stories (author, story_name, story)
VALUES
('$_POST[author]','$_POST[story_name]', '$_POST[story]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Story Submitted!";
mysql_close($con)
Where would I add that string in this?
Upvotes: 0
Views: 254
Reputation: 1770
//USE IN THIS WAY THE QUERY WILL RUN PROPERLY WITH mysql_real_escape_string
$sql= 'INSERT INTO stories (author, story_name, story)
VALUES
('.mysql_real_escape_string($_POST[author]).',
'.mysql_real_escape_string($_POST[story_name]).',
'.mysql_real_escape_string($_POST[story]).')';
Upvotes: 1
Reputation:
You need to escape any variable values you're including in your query. So in your code these would be:
$_POST['author']
$_POST['story_name']
$_POST['story']
So change your $sql
variable to look like:
$author = mysql_real_escape_string($_POST['author']);
$story_name = mysql_real_escape_string($_POST['story_name']);
$story = mysql_real_escape_string($_POST['story']);
$sql= "
INSERT INTO stories (author, story_name, story)
VALUES ('$author','$story_name', '$story')
";
You should probably also add isset
or empty
checks when using the $_POST
variables to avoid notices if they don't exist. Finally, you'd be better served to use PDO with prepared statements than the less robust mysql extension.
Upvotes: 2
Reputation: 329
put POST variables into new variables and then apply mysql_real_escape_string, and finally put new variables into the SQL statement
Here's the code:
include("dbconnect.php");
mysql_select_db("scratch", $con);
$author = mysql_real_escape_string($_POST[author]);
$story_name = mysql_real_escape_string($_POST[story_name]);
$story=mysql_real_escape_string($_POST[story]);
$sql= "INSERT INTO stories (author, story_name, story)
VALUES
('$author','$story_name', '$story')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Story Submitted!";
mysql_close($con);
Upvotes: 0