0

Can someone who know MySQL help me with this? I've done DB2 connects but don't know why my MySQL statement is failing. I have a form that collects contact information that then rolls to this page. I am trying to collect this information and store it into a database table. From there it sends me an email to let me know someone has filled it out. I'm guessing it has something to do with my apostrophes but I'm not sure on that. Like I said I don't work with MySQL very often so I am trying to figure out what it is I did wrong on it.

$firstname = trim($_POST['firstname']);
$lastname = trim($_POST['lastname']);
$homephone = trim($_POST['homephone']);
$cellphone = trim($_POST['cellphone']);
$email = trim($_POST['email']);

date_default_timezone_set("America/Indiana/Indianapolis");
$datetime = date(mdyHis);

$to = "email@gmail.com";
$subject = "New Training Completion";
$text = "A new person has completed their online training. Go check to create the certificate and mark them as complete.";

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO completion (firstname, lastname, homephone, cellphone, email, datetime) VALUES ('$firstname', '$lastname', $homephone, $cellphone, '$email', $datetime)";

if (mysqli_query($conn, $sql)) {
     mail($to,$subject,$text);
     header("Location: /sucess.html");

} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
lsbowman98
  • 19
  • 3
  • 3
    Your problem is the apostrophes in the INSERT query. It is not wise to insert php variables directly into the sql query. You are completely open to the SQL Injection attack. I recommend using "prepared statements". – Petr Fořt Fru-Fru Dec 21 '21 at 19:55
  • 1
    If you are only starting to learn PHP then you should learn PDO instead of mysqli. PDO is much easier and more suitable for beginners. Start here https://phpdelusions.net/pdo & https://websitebeaver.com/php-pdo-prepared-statements-to-prevent-sql-injection – Dharman Dec 21 '21 at 19:57

0 Answers0