开发者

php form not writing form data into mysql database

开发者 https://www.devze.com 2023-04-11 20:32 出处:网络
I have to code below - updated php code if(empty($_POST[\'formEmail\'])) { $errorMessage .= \"<li>You forgot to enter your email</li>\";

I have to code below - updated

php code

    if(empty($_POST['formEmail'])) 
    {
        $errorMessage .= "<li>You forgot to enter your email</li>";
    }

    $varEmail = $_POST['formEmail'];

    if(empty($errorMessage)) 
    {

        $db = mysql_connect("servername","username","password");
        if(!$db) die("Error connecting to MySQL database.");
        mysql_select_db("tableName" ,$db);



    $sql = "INSERT INTO emails(email) VALUES ('$varEmail')";

    mysql_query($sql);


echo "Details added";
$_SESSION['status'] = 'success';
 }

exit();


    }

function PrepSQL($value)
{
    // Stripslashes
    if(get_magic_quotes_gpc()) 
    {
        $value = stripslashes($value);
    }

    // Quote
    $value = "'" . mysql_real_escape_string($value) . "'";

    return($value);
}
?>

form code

    <?php
i开发者_开发问答f(!empty($errorMessage)) 
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
    }
    ?>

<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>
<label for='formEmail'>Sign up to be notified when we go live!</label><br/>
<input type="text" name="formEmail" maxlength="50" value="<?=$varEmail;?>" />
</p>
<input type="submit" name="formSubmit" value="Submit" />
</form>

I'm not getting any errors and as far as I can tell the syntax looks fine but its not putting the email information into the database. Anyone have an idea of whats going on? As a side note I am a newb to all php.


You've forgotten to run the query! Put

mysql_query($sql);

straight after

$sql = "INSERT INTO emails(email) VALUES ('$varEmail')";

Make sure you run the $_POST variable through mysql_real_escape_string as well:

$varEmail = mysql_real_escape_string($_POST['formEmail']);

This will help protect you from SQL Injection attacks.

EDIT

One more tiny thing, I guess you want to set the session variable success when the form has submitted successfully. to do that you'll need to move

echo "Details added";
$_SESSION['status'] = 'success';

within the same if structure as the SQL query is run, otherwise it will never be set


Try:

    $db = mysql_connect("servername","username","password");
    if(!$db) die("Error connecting to MySQL database.");
    mysql_select_db("tableName" ,$db);


    $sql = sprintf("INSERT INTO emails(email) VALUES ('%s')",mysql_real_escape_string($varEmail));
    $results = mysql_query($sql);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号