Unable to save data in database

$name_error = $email_error = "";
$name = $email = "";


if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $name_error = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $name_error = "Only letters and white space allowed";
        }
    }

    if (empty($_POST["email"])) {
        $email_error = "Email is required";
    } else {
        $email = test_input($_POST["email"]);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $email_error = "Invalid email format";
        }
    }

if ($name_error == '' and $email_error == '' ){
        $message_body = '';
        unset($_POST['submit']);
        foreach ($_POST as $key => $value){
            $message_body .=  "$key: $value\n";
        }
$query = "INSERT INTO clients(name,email) ";
        $query .= "VALUES('$name', '$email') ";

        $create_user = mysqli_query($mysqli, $query);

        if (!$create_user) {
            die("QUERY FAILED. " . mysqli_error($mysqli));
        }


}

I am getting the email from localhost but the user entry is not saving in the database. When I click submit button, msg sent successfully without any error. Please help. :banghead:

I can’t see anything obvious in the code, if you use the same values and run the query manually through phpmyadmin or whatever you use, does it work then?

Tiny other point, in your name validation, how might James O’Connor fill out the form successfully? Or David Wynn-Jones?

**

UPDATE: Now, the form data is storing in the database, actually there was a problem in the mail function, so i removed the empty strings and its works BUT, when i click submit button on empty form, it is also storing the empty values to database like given in below screenshot

**

http://image.prntscr.com/image/746b787a5e174804a21859e7fc5c3e00.png

This is my html

 <fieldset>
            <input placeholder="Your name" type="text" name="name" value="<?= $name ?>" tabindex="1" autofocus>
            <span class="error"><?= $name_error ?></span>
        </fieldset>
        <fieldset>
            <input placeholder="Your Email Address" type="text" name="email" value="<?= $email ?>" tabindex="2">
            <span class="error"><?= $email_error ?></span>
        </fieldset>

I know there is some issue to write James O etc, will fix it later.

Are the fields empty, or might they have a single space in them? If they’re actually empty, then they shouldn’t come through at all and won’t exist, and empty() should return true and create your error message. So I wonder if they’re coming in as blank strings which won’t be seen. Perhaps you should trim them before you check.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.