mOna mOna - 4 months ago 14
PHP Question

secure insertion of form data containing arrays into mysql database

I found many answers about how to insert form data into mysql using PDO, also I found some answers related to insert data from an array like this one but actually my problem is related to the third question in my form for which I am not sure if I wrote the query in a correct way

This is my code but it give me this error:


PHP Parse error: syntax error, unexpected ';' in line ... (the line related to insert statement)


<?php
session_start();

if(isset($_POST['submit']))
{
$_SESSION['q1'] = $_POST['q1'];
$_SESSION['q2'] = $_POST['q2'];
$_SESSION['q3'] = implode(',', $_POST['genre']);

$q1 = mysql_real_escape_string($_SESSION['q1']);
$q2 = mysql_real_escape_string($_SESSION['q2']);
$q3 = mysql_real_escape_string($_SESSION['q3']);

$conn = new PDO('mysql:dbname=Application;host=localhost;charset=utf8', 'user', 'xxxx');
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('INSERT INTO test (q1, q2, q3) VALUES (:q1, :q2, :q3)');
$stmt->execute(array(':q1' => $q1,':q2' => $q2,':q3' => ".$q3."));
}

catch(Exception $e) {
echo 'Exception -> ';
var_dump($e->getMessage());
}

header('Location: Thankyou.php');
exit;
}
?>

Answer

First of all don't mix mysql with PDO, Also use try with catch exception and

change

$stmt->execute(array(':q1' => $q1,':q2' => $q2,':q3' => ".$q3."));

to

$stmt->execute(array(':q1' => $q1,':q2' => $q2,':q3' => $q3));