Where to put & ldquo; Mysql_real_escape_string & rdquo; In this code?

advertisements

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?


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.