我对php和mysql很新。我正在尝试创建一个php表单 哪些数据将存储在后端Mysql数据库中
我创建了两个php文件
这两个文件都有一个require_once(DB_Login.php)函数 连接到Mysql DB
Form.php的内容 ---
<html>
<head>
<body>
<form action="insert.php"
method="POST">
<?php
require_once('DB_Login.php');
$sql=mysql_query("Select * from Department");
echo '<table border=1px>';
echo '<th>DepartmentId</th> <th>Department_Name</th><th>
Description</th>';
$datas=array();
while($data=mysql_fetch_array($sql))
{
$datas[]=$data;
//Running a loop all contents in the Mysql Table
echo '<tr>';
echo '<td>.$datas[\'Dept_Id\'] </td> <td>.$datas[\'Dname\']</td>
<td>.$datas[\'Description\']</td>';
echo '</tr>';
}
echo'<tr>';
echo'<td><input type=\"text\" name=\"Dept_Id\" id=\"Dept_Id\"></td><td>
<input type=\"text\" name=\"Dname\" id=\"Dname\"></td> <td><input
type=\"text\" name=\"Description\" id=\"Description\"></td>';
echo'</tr>';
echo '</table>';
echo'<input type="submit" value="SEND">';
?>
</form>
</body>
</head>
</html>
insert.php的内容 -
<?php
require_once('DB_Login.php');
$Didtext = mysql_real_escape_string($_POST['Dept_Id']);
$Dnametext=mysql_real_escape_string($_POST['Dname']);
$Desctext=mysql_real_escape_string($_POST['Description']);
echo $Didtext;
echo $Dnametext;
$adddept="INSERT INTO Department('Dept_Id','Dname','Description')
values('$Didtext','$Dnametext','$Desctext')";
$result = mysql_query($adddept);
if($result)
{
echo("<br>Input data is succeed");
}
else
{
echo("<br>Input data failed");
}
?>
问题认为值没有传递给insert.php
$Didtext = mysql_real_escape_string($_POST['Dept_Id']);
$Dnametext=mysql_real_escape_string($_POST['Dname']);
$Desctext=mysql_real_escape_string($_POST['Description']);
运行此代码后,我收到消息输入数据失败。 我做了很多搜索这个问题。 我使用 id 属性将元素值传递给insert.php
请帮助!!!
答案 0 :(得分:0)
<强>更新强>
将 Form.php 代码更改为:
...
...
echo '<tr>';
echo '<td><input type="text" name="Dept_Id" id="Dept_Id"></td>';
echo '<td><input type="text" name="Dname" id="Dname"></td>';
echo '<td><input type="text" name="Description" id="Description"></td>';
echo '</tr>';
echo '</table>';
无需在双引号之前写" \"
。
您没有传递存储值的变量。在 insert.php :
中执行以下更改$adddept="INSERT INTO Department('Dept_Id','Dname','Description')
values('".$Didtext."','".$Dnametext."','".$Desctext."')";
注意:如果Dept_Id
为int
,则无需在变量'
之前和之后使用$Didtext
:
$adddept="INSERT INTO Department('Dept_Id','Dname','Description')
values(".$Didtext.",'".$Dnametext."','".$Desctext."')";
答案 1 :(得分:0)
标记列名时不应使用撇号('
)。删除它们。
您的插入查询应如下所示:
$adddept="INSERT INTO Department(Dept_Id, Dname, Description)
VALUES('$Didtext','$Dnametext','$Desctext')";
另外,请确保表单中的$_POST
值与输入字段的name
HTML标记相同。在您的输入字段中指定名称标记时,您不需要使用反斜杠(\
),您使用'
来回显并使用"
分配HTML标签。
<input type="text" name="Dept_Id" id="Dept_Id">
并仔细检查您在查询中使用的表名和列名,因为这些数据区分大小写。
注意:您不应再使用deprecated mysql_*
API,而是使用mysqli_*
prepared statement。