I learned in school to do something like the below to insert data into SQL via $_POST
ed form data.
$title = mysql_escape_string($_POST["newstitle"]);
$body = mysql_escape_string($_POST["newsbody"]);
$addnews = $db->query("
INSERT INTO news
VALUES (CURRENT_DATE, '$body', '$title', '')
");
However, it was fairly recently I was told I should be using the below instead:
$addnews = $db->prepare("
INSERT INTO news
VALUES (CURRENT_DATE, :body, :title, '')
");
$addnews->execute(array(
':body' => $_POST["newsbody"],
':title' => $_POST["newstitle"]));
What benefit does the second snippet of code offer? My professor in the aforementioned course was very traditional and I imagine was teaching an archaic way of doing things. He did use a lot of PDO, but never for the above example. And yes, I know mysql_escape_string()
is deprecated, but that is how I was taught. I'm trying to make an effort to change my method to be more appropriate for current trends.