I'm a complete beginner to php. My code has a feedback form that sends data to mysql. I'm not sure how to secure this against SQL injection. I would love your help.
Here is the code:
<?php
if(isset($_POST["send_message"])){
$hostname='localhost';
$username='';
$password='';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=dbname",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$message = $_POST['message'];
$sql = "INSERT INTO tbl_contact (message) VALUES ('$message')";
if ($dbh->query($sql)) {
include "thanks.php";
} else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
Update: I'm trying to use prepared statements and bind parameters but I get an: Uncaught Error: Call to undefined method PDOStatement::bind_param().
Here is the updated code:
<?php
if(isset($_POST["send_message"])){
$dbConnection = new PDO('mysql:dbname=sondagg9_submit;host=localhost;charset=utf8', 'sondagg9_travadm', 'Mc%F}SrGk5m5#t<Crb4?');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbConnection->prepare('INSERT INTO tbl_contact (message) VALUES (?)');
$stmt->bind_param('s', $message);
$message = $_POST['message'];
$stmt->execute();
$result = $stmt->get_result();
}
?>
SOLVED: Thanks to your comments, I've been able to solve the issue this way:
<?php
if(isset($_POST["send_message"])){
$dbConnection = new PDO('mysql:dbname=sondagg9_submit;host=localhost;charset=utf8', 'sondagg9_travadm', 'Mc%F}SrGk5m5#t<Crb4?');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$message = $_POST['message'];
$stmt = $dbConnection->prepare('INSERT INTO tbl_contact (message) VALUES (:message)');
$stmt->execute([ 'message' => $_POST['message'] ]);
}
?>