I am currently coding a PHP script that connects to a database and inserts a phone number and IP address if either item is not present in the table. I believe I have completed it and it is working but I want to make sure that I have used best practices in regards to security. I have read here about how to connect to MySQL and query it using a PDO and a prepared statement. I also read on Stack Overflow that had a fantastic explanation on how to do this. However, this is now a few years old.
I would like to know if my code follows current best practices and that it is secure against SQL injection.
if( isset($_POST['submit']))
{
//user data
$name = $_REQUEST['fullname'];
$numbers = $_REQUEST['number'];
$bedrooms = $_REQUEST['bedrooms'];
$date = $_REQUEST['date'];
$movingFrom = $_REQUEST['from-postcode'];
$movingTo = $_REQUEST['to-postcode'];
$typeOfJob = $_REQUEST['typeOfJob'];
$additionalInfo= $_REQUEST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$id= NULL;
//connection variables
$host='localhost';
$user='root';
$pass='';
$db='lookup';
$chset='utf8mb4';
$dns = "mysql:dbname=$db;host=$host;charset=$chset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
//Try to create a new PDO object and pass the vars
$connection = new PDO($dns, $user, $pass, $options);
//prepare the database for data and exectue
$stmt = $connection->prepare("SELECT id, numbers, ip FROM numbers");
$stmt->execute();
//Loop through table and check for numbers and ips
//If present set var to true and break from loop
$present = false;
foreach ($stmt->fetchAll() as $k=>$v)
{
if($v['ip'] == $ip or $v['numbers'] == $numbers)
$present = true;
break;
}
//If data present I will be redirecting and informing user
if($present)
{
//TODO: send to different pages
echo "present";
}
//Else insert the data into the table
else
{
$sql = "INSERT INTO numbers (id, numbers, ip) VALUES (NULL, '$numbers', '$ip')" ;
$stmt = $connection->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':numbers', $numbers);
$stmt->bindParam(':ip', $ip);
$stmt->execute();
echo "Woohoo";
}
} catch (PDOException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
There is more code in the if statement but it is irrelevant here as it is for the HTML.