使用表单发布到数据库时遇到问题

时间:2012-04-17 16:50:49

标签: php mysql database post

我有一个简单的表单,其中包含一些PHP代码,可以向数据库发布一些简单的信息。

与数据库的连接很好,因为它显示我手动输入的项目,我想要它的确切方式;然而。我无法让它从表单发布到数据库中。我已经修改了许多代码而没有运气。有人看到我遗失的任何东西吗?这是代码:

<center>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">

    <strong><h2><br><br>Enter in my guestbook!</h2></strong><br>
    <h3>Nickname:</h3><input type="text" name="guestbook_name" maxlength="25"><br>
    <h3>Write About Your Day:</h3><textarea name="guesbook_message" rows="6" cols="60"       maxlength="255"></textarea><br>
    <input type ="submit" value="POST">

</form>

<br>
<hr>
<br>

<?php

    if (mysql_connect('localhost', 'root', 'root') && mysql_select_db('mydb')) {

    //echo 'Connected to the database!';

    $time = gmdate("l dS \of F Y h:i:s A");
    $errors = array();

    if (isset($_POST['guestbook_name'], $_POST['guestbook_message'])) {

        echo 'Set data!';

        $guestbook_name = mysql_real_escape_string(htmlentities(     $_POST['guestbook_name'])); 
        $guestbook_message = mysql_real_escape_string(htmlentities(     $_POST['guestbook_message'])); 

        if (empty($guestbook_name) || empty($guestbook_message)) {
        $errors[] = 'All fields are required.';
        }

        if (strlen($guestbook_name)>25 || strlen($guestbook_message)>250){
        $errors[] = 'One or more fields exceeded the character limit!'; 
        }

        if (empty($erros)) {
            $insert = "INSERT INTO guestbook VALUES     ('','$time','$guestbook_name','$guestbook_message')";
            if (mysql_query($insert)){
                 header ('Location: '.$_SERVER['PHP_SELF']);
            } else {
                $errors[] = 'Something went wrong. Try again.';
            }

        } else {
            foreach($errors as $error) {
                echo'<p><strong>'.$error.'</strong></p>'; 
            }

        }

    }

    // display entries 
    $entries = mysql_query("SELECT timestamp, name, message FROM guestbook ORDER BY timestamp DESC");

    if (mysql_num_rows($entries)==0){
        echo 'No entries, yet.';
        } else { 
            //echo 'Entries found.'; 

            while ($entries_row = mysql_fetch_assoc($entries)){
                $entries_timestamp = $entries_row['timestamp'];
                $entries_name = $entries_row['name'];
                $entries_message = $entries_row['message'];
                echo '<p><strong>Posted by '.$entries_name.' on     '.$entries_timestamp.'</strong>:<br><br>'.$entries_message.'</p><br><br>';

            }
        }

} else {
    echo 'Could not connect at this time.';
} 


?>

</center>

我的主要问题是提交数据库,任何帮助都会很棒,谢谢!

Kyle B。

2 个答案:

答案 0 :(得分:0)

我们需要查看您的数据库表结构与insert sql语句,看看您是否正确插入。

插入失败的最可能原因是没有设置一个设置为NOT NULL的字段值(通过不插入值或具有空/错误类型的变量)。

但更常见的问题是:

wrong table or field names
not having the enough privelages on your database user account

答案 1 :(得分:0)

也许错字?

if (empty($erros)) {

我认为正确的名称是$ errors (注意R)