Hi guys i dont know what im doing wrong but my tables are correct, php error is on and it doesnt insert
I can get both first name and email echoed
<?php
if (isset($_POST['subs'])) {
function html_escape($html_escape) {
$html_escape = htmlspecialchars($html_escape, ENT_QUOTES | ENT_HTML5, 'UTF-8');
return $html_escape;
}
$name=html_escape($_POST['name']);
$email=html_escape($_POST['email']);
if (empty($name) || empty($email)) {echo"<div class='alert alert-danger'>Please enter both name and email address</div>";}
else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo"<div class='alert alert-danger'>Invalid email address, please enter a correct email address!</div>";
}
else {
echo "INSERT into subs (first_name, email) VALUES ('$name','$email')";
$insert=mysql_query("INSERT into subs (first_name, email) VALUES ('$name','$email')");
if ($insert) {echo"<div class='alert alert-success'>Thank you for subscribing with us</div>";}
}
}}
?>
first of all, are you connected to mysql before running your query?
$conn=mysql_connect('localhost', 'your_db_username', 'your_db_password');
if(!$conn){
die('Cannot connect to mysql');
}
mysql_select_db('your_db_name');
Then, when you're sure you're connected to the db and your query is still not working, add or die(mysql_error())
after your query like this, this will help you know what's going wrong with your insert:
$insert=mysql_query("INSERT into subs (first_name, email)
VALUES ('$name','$email')")
or die(mysql_error());
As a general point, using the PDO class is preferred, and may give you more information about what the problem is.
e.g.
$pdo = new \PDO('mysql:host=localhost;dbname=<database_name>', '<database_username>', '<database_password>');
$sql = "INSERT into subs (first_name, email) VALUES (:name,:email)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$result = $stmt->execute();
This gives a lot of benefits. Take my word for it, or give "benefits of PDO" a quick Google.
$query = "INSERT INTO subs (first_name, email) VALUES ('" . $name . "','" . $email . "') ";
$insert = mysql_query($query);