artwired artwired - 16 days ago 8
MySQL Question

MySQL and PHP code allowing empty form field data

I have seen many similar questions on this site but I have not yet found a solution for my code. I did use if(isset($_POST['submit'])) {} and the if statements to go along with it to try and stop my script from inserting empty form field data but it hasn't worked yet. Just a note; I am aware of the security flaws in my code. I'm just trying to keep it simple so it will be easier for everyone to help me :) Here's what I have:

<body>

<?php

if (isset($_POST['submit'])) {

$dbc = mysqli_connect('localhost', 'username', 'password', 'bcd_email_app')
or die('Error connecting to MySQL server');

$query = "INSERT INTO email_subscribers (name, username, email)" .
"VALUES ('$name', '$username', '$email')";

mysqli_query($dbc, $query)
or die('Error querying database');

echo 'Thanks for subscribing '. $username .'!!<br />';
echo '<a href="index.php">Go Back</a>';

mysqli_close($dbc);

$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];

$output_form = false;

//checking that all form fields have been filled out and if not displaying the form with sticky data
if (empty($name) && (empty($username) && (empty($email)))) {
echo 'Please enter your information for all fields. <br />';
$output_form = true;
}
if (empty($name) && (!empty($username) && (!empty($email)))) {
echo 'Please enter your name. <br />';
$output_form = true;
}
if (!empty($name) && (empty($username) && (!empty($email)))) {
echo 'Please enter your username. <br />';
$output_form = true;
}
if (!empty($name) && (!empty($username) && (empty($email)))) {
echo 'Please enter your email address. <br />';
$output_form = true;
}
if (empty($name) && (empty($username) && (!empty($email)))) {
echo 'Please enter your name and username. <br />';
$output_form = true;
}
if (empty($name) && (!empty($username) && (empty($email)))) {
echo 'Please enter your name and email address. <br />';
$output_form = true;
}
if (!empty($name) && (empty($username) && (empty($email)))) {
echo 'Please enter your username and email. <br />';
$output_form = true;
}
} else {
$output_form = true;
}
if ($output_form) {

?>


Form Markup Here


</body>


I also tried to say if name && username && email is not empty like this:

if (isset($_POST['submit'])) && (!empty($_POST['name'])) && (!empty($_POST['username'])) && (!empty($_POST['email']))) {...}


with the post submit, and that didn't do anything. Is there a solution? Did I do this totally wrong? lol

Thanks in advance for your help!

Answer

How do you expect to not insert empty data if you validate after inserting it into db?

First validate the data and show an error if your data is empty and insert it into db only if your validation is successful.