我无法在我的mysql数据库中向我的表添加数据

时间:2013-08-10 21:26:58

标签: php mysql forms

请参阅下面的php代码:

我使用php中的<<< _END _END标签在html表单中构建了html表单和下拉菜单。我还在htmlform的顶部添加了以下php代码,我相信这些代码可以让我输入学生姓名,学生ID并从表格的下拉菜单中选择一门课程。一旦在表单中输入了这3个值,就应该将信息添加到我的mysql数据库中的表注册中。但我没有运气搞清楚......

//connect3.php--login information to my mysql database//

<?php
 define ('HOST', 'localhost');
 define ('USER', 'root');
 define ('PASS', '******');
?>


// html form and connection code//
    <?php
     include 'connect3.php';
     $link = mysql_connect (HOST, USER, PASS) or die(mysql_error());
     mysql_select_db ('milleruniversity', $link);

// Added mysql_real_escape() to protect against SQL-Injection
$code        = mysql_real_escape( $_POST['code'] ); 
$uid         = mysql_real_escape( $_POST['uid'] );
$studentname = mysql_real_escape( $_POST['studentname'] );

// Insert a row of information into the table "enrolment"

$query = "INSERT INTO enrolment (code, uid, studentname) VALUES('$code', '$uid', '$studentname')";
if(mysql_query($query)){
echo "inserted";}
else{
echo "fail";}
echo <<<_END
<table border='1'cellpadding="10">
<tr>
<td>
<h4>Miller University Registration Form</h4>
<p>Please Register as a new Student or current student for the following courses below.</p>
</td>
</tr>
<form action="draft5.php" method="post"><pre>
<tr>
<td>
  Student Name <input type="text" name="studentname" maxlength="30"/>
</td>
</tr>
<tr>
<td>
   Student ID <input type="text" name="uid" maxlength="11"/>
</tr>
</td>
<tr>
<td>
Select a course <select name="code" size="1">
<option value="DC-00040">Digital Communications</option>
<option value="VC-00030">Visual Culture</option>
<option value="WP-00080">World Politics</option>
</select>
</tr>
</td>
<tr>
<td>
        <input type="submit" value="Submit to Register" />
</tr>
</td>
</pre></form>
</table>
_END;

mysql_close($link);

?>

1 个答案:

答案 0 :(得分:0)

在我看来,您使用此draft5.php页面来显示表单并在数据库中插入一行。在这种情况下,问题可能来自$ _POST数据周围缺少的isset()。 (第一次加载页面时,未设置POST值)。 您可以使用此代码:

if( (isset($_POST['code']) AND (isset($_POST['uid']) AND (isset($_POST['studentname']){
//process the data base treatment and display an acknoledgment of the insert
// Check if these new code, uid and studentname respect the primary key constraint


}

else{
// Display your form
}

您还可以考虑在表和colomns的名称周围使用反引号。

如果您想阻止同一个学生在同一课程中注册两次,您需要在表格中添加主键。但这还不够,确实如果你在主键上执行带有约束违规的插入请求,MySql将返回错误。您可以做的是检查插入请求之前是否存在密钥,如果是,则通知用户,如果不执行插入请求。

相关问题