Add validation to form using php

Hi,

I created an order form in php but I need to add validation to the form field e-mail.
I tried to add

// Check format email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = “Invalid email format”;
}

To the php code but I don’t succeed in making this work.
The code I have in the 3-process.php file in which I connect to the database and save order in the database is:

<?php
// (A) PROCESS RESULT
$result = "";


// (B) CONNECT TO DATABASE - CHANGE SETTINGS TO YOUR OWN!
$dbhost = "localhost";
$dbname = "dbname";
$dbchar = "utf8";
$dbuser = "user";
$dbpass = "pword";
try {
  $pdo = new PDO(
    "mysql:host=$dbhost;dbname=$dbname;charset=$dbchar",
    $dbuser,
    $dbpass,
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
  );
} catch (Exception $ex) {
  $result = $ex->getMessage();
}

// (C) SAVE ORDER TO DATABASE
if ($result == "") {
  try {
    $stmt = $pdo->prepare("INSERT INTO `orders` (`name`, `adres`, `postcode`, `woonplaats`, `email`, `qty1`, `qty2`, `qty3`) VALUES (?,?,?,?,?,?,?,?)");
    $stmt->execute([$_POST["name"], $_POST["adres"], $_POST["postcode"], $_POST["woonplaats"], $_POST["email"], $_POST["qty1"], $_POST["qty2"], $_POST["qty3"]]);
  } catch (Exception $ex) {
    $result = $ex->getMessage();
  }
}

// (D) SEND ORDER VIA EMAIL
if ($result == "") {
  $to = $_POST["[email protected]"];
  $subject = "Order ontvangen";
  $message = "";
  foreach ($_POST as $k => $v) {
    $message .= "$k - $v\r\n";
  }
  if (!@mail($to, $subject, $message)) {
    $result = "Error sending mail!";
  }
}

And in the order form I put:
<body>
  <?php include "./includes/topnav.html" ?>
  <h1> <?= PROJECT_NAME ?></h1>

  <?php
  // (A) PROCESS ORDER FORM
  if (isset($_POST["name"])) {
    require "3-process.php";
    header('Location: thankyou.php');
  }
  ?>

  <!-- (B) ORDER FORM -->

I hope somebody could help me with this, I’ve been struggeling for days!

Sponsor our Newsletter | Privacy Policy | Terms of Service