I have read a lot about sql injection and I understand how it could cause problems (ie: DROP TABLE __ etc). But I am unsure how the tutorials I have followed actually prevent this from happening. I am just learning PDO and I think I understand it.
Is this code safe from SQL injection? and why is it? (It takes quite a bit more work using these prepared statements so I want to be sure I am not just wasting my time – also if the code can be improved please let me know!)
$conn = new PDO("mysql:host=$DB_HOST;dbname=$DB_DATABASE",$DB_USER,$DB_PASSWORD);
// Get the data
$firstname = $_POST["v_firstname"];
$lastname = $_POST["v_lastname"];
$origincountry = $_POST["v_origincountry"];
$citizenship = $_POST["v_citizenship"];
$gender = $_POST["v_gender"];
$dob = $_POST["v_dob"];
$language = $_POST["v_language"];
$landing = $_POST["v_landing"];
$email = $_POST["v_email"];
$phone = $_POST["v_phone"];
$cellphone = $_POST["v_cellphone"];
$caddress = $_POST["v_caddress"];
$paddress = $_POST["v_paddress"];
$school = $_POST["v_school"];
$grade = $_POST["v_grade"];
$smoker = $_POST["v_smoker"];
$referred = $_POST["v_referred"];
$notes = $_POST["v_notes"];
//Insert Data
$sql = "INSERT INTO clients (firstname, lastname, origincountry, citizenship, gender, dob, language, landing, email, phone, cellphone, caddress, paddress, school, grade, smoker, referred, notes)
VALUES (:firstname, :lastname, :origincountry, :citizenship, :gender, :dob, :language, :landing, :email, :phone, :cellphone, :caddress, :paddress, :school, :grade, :smoker, :referred, :notes)";
$q = $conn->prepare($sql);
$q->execute(array(':firstname'=>$firstname,
':lastname'=>$lastname,
':origincountry'=>$origincountry,
':citizenship'=>$citizenship,
':gender'=>$gender,
':dob'=>$dob,
':language'=>$language,
':landing'=>$landing,
':email'=>$email,
':phone'=>$phone,
':cellphone'=>$cellphone,
':caddress'=>$caddress,
':paddress'=>$paddress,
':school'=>$school,
':grade'=>$grade,
':smoker'=>$smoker,
':referred'=>$referred,
':notes'=>$notes));
Yes, the code is safe, as PDO will properly escape and quote the array of parameters for you.