gpt4 book ai didi

php - 我无法将数据添加到我的 mysql 数据库中的表中

转载 作者:行者123 更新时间:2023-11-30 01:24:31 25 4
gpt4 key购买 nike

请参阅下面的 php 代码:

我已经使用 php 中的 <<<_END _END 标签构建了 html 表单和 html 表单中的下拉菜单。我还在 htmlform 的顶部添加了以下 php 代码,我相信它可以让我输入学生姓名、学生 ID 并从表单的下拉菜单中选择类(class)。在表单中输入这 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);

?>

最佳答案

在我看来,您使用这个 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
}

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

如果您想防止同一学生在同一类(class)中注册两次,您需要在表中添加主键。但这还不够,实际上,如果您在主键上执行违反约束的插入请求,MySql 将返回错误。您可以做的是在插入请求之前检查 key 是否存在,如果存在则通知用户,如果不存在则执行插入请求。

关于php - 我无法将数据添加到我的 mysql 数据库中的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18166513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com