benjiman benjiman - 1 year ago 71
MySQL Question

PHP and MySQL form submit

In this block of code where do I put mysqli_real_escape_string() ?

Or if you have a better way of writing the whole block I'm interested to hear.

$title = ($_POST["title"]);
$date = ($_POST["date"]);
$content = ($_POST["content"]);

$query = "INSERT INTO months (";
$query .= " title, date, content ";
$query .= ") VALUES (";
$query .= " '{$title}', '{$date}', '{$content}' ";
$query .= ")";
mysqli_query($connection, $query); ?>

Answer Source

It would be the best to use prepared statements.

$stmt = mysqli_prepare($connection, "INSERT INTO months (title, date, content) 
                                VALUES(?, ?, ?)");

mysqli_stmt_bind_param($stmt, "sss", $title, $date, $content);
$title = $_POST["title"]; 
$date = $_POST["date"]; 
$content = $_POST["content"]; 

When using an escape function and string concatenation there might still be cases in which sql injection is possible. Prepared Statements work differently, so they are secure against sql injection.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download