dongpao1918 2011-10-10 18:26
浏览 54

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

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
if(!empty($errorMessage)) 
{
echo("<p>There was an error with your form:</p>
");
echo("<ul>" . $errorMessage . "</ul>
");
    }
    ?>

<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.

  • 写回答

2条回答 默认 最新

  • drqxfmfa804578 2011-10-10 18:29
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型