php表单没有将表单数据写入mysql数据库

时间:2011-10-10 18:26:25

标签: php mysql forms phpmyadmin database-connection

我必须在下面编码 - 更新

php代码     

    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);
}
?>

表单代码

    <?php
if(!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>

我没有收到任何错误,据我所知,语法看起来很好,但它没有将电子邮件信息放入数据库。任何人都知道最近会发生什么?作为旁注,我是所有php的新手。

2 个答案:

答案 0 :(得分:6)

您忘记运行查询了!放

mysql_query($sql);

直接

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

确保您通过$_POST运行mysql_real_escape_string变量:

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

这有助于保护您免受SQL Injection attacks

的攻击

修改

还有一件小事,我想你想在表单成功提交时设置会话变量success。要做到这一点,你需要移动

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

在与运行SQL查询相同的if结构内,否则将永远不会设置

答案 1 :(得分:2)

尝试:

    $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);