[英]Entering secondary data into pre-existing database
我需要协助。 我写了一个脚本,将名字和姓氏放入数据库中。 这可以正常工作。 然后,我编写了一个脚本来显示这些名称以及每个名称4个文本字段,可以在其中键入学生分数,然后将其存储在数据库中。 来自数据库的名称正确显示,并且文本字段正确显示,但是,当我尝试将数字放在字段中时,它没有将数字放入数据库中并生成“未定义索引”错误。 我已经为此工作了一段时间,但没有得到。 谢谢你的帮助。 我的代码如下。 谢谢。
<html>
<body>
<form action="pts_summary.php" method="post">
<table border="1">
<tr>
<th>Student Name</th>
<th>First Hour</th>
<th>Second Hour</th>
<th>Third Hour</th>
<th>Fourth Hour</th>
</tr>
<br>
<?php
$hour1 = $_POST['hour1'];
$hour2 = $_POST['hour2'];
$hour3 = $_POST['hour3'];
$hour4 = $_POST['hour4'];
$con=mysqli_connect("localhost","root","","srrdb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * From students");
while($row = mysqli_fetch_array($result))
{
echo "<tr>"."<td>".$row['fname']." ".$row['lname']."</td>".
"<td>".'<input type="text" name="hour1">'."</td>".
"<td>".'<input type="text" name="hour2">'."</td>".
"<td>".'<input type="text" name="hour3">'."</td>".
"<td>".'<input type="text" name="hour4">'."</td>"."</tr>";
}
if (isset ($_POST['submit']))
{
$sql="INSERT INTO students (hour1, hour2, hour3, hour4)
VALUES ('".$hour1."','".$hour2."','".$hour3."','".$hour4."')";
}
mysqli_close($con);
?>
</table>
<br><input type="submit" value="SUBMIT" name="submit">
</form>
</body>
</html>
您甚至在检查是否已按下“提交”按钮之前都尝试获取帖子数据。 如果未按下提交按钮,则$ _POST ['hour#']字段中将没有值,这将引发未定义的索引错误。 像这样在提交支票之后扔那些行。
if (isset ($_POST['submit']))
{
$hour1 = $_POST['hour1'];
$hour2 = $_POST['hour2'];
$hour3 = $_POST['hour3'];
$hour4 = $_POST['hour4'];
$sql="INSERT INTO students (hour1, hour2, hour3, hour4)
VALUES ('".$hour1."','".$hour2."','".$hour3."','".$hour4."')";
}
未定义的索引通知是由于使用$_POST[...]
而引起的,而不检查它们是否已设置。 您的数据未插入数据库,因为您仅设置INSERT
查询-
$sql="INSERT INTO students...
但您永远不会执行查询。
mysqli_query($con,$sql);
尝试-
if (isset ($_POST['submit'])){
// put these inside isset() to prevent undefined index notices
$hour1 = $_POST['hour1'];
$hour2 = $_POST['hour2'];
$hour3 = $_POST['hour3'];
$hour4 = $_POST['hour4'];
$sql="INSERT INTO students (hour1, hour2, hour3, hour4)
VALUES ('".$hour1."','".$hour2."','".$hour3."','".$hour4."')";
//missing the query line
// Insert or die with error message
$update = mysqli_query($con,$sql) or die(mysqli_error($con));
}
另外,您使用的是未经消毒的$_POST
数据,因此您可以使用SQL注入。 无论是使用消毒mysqli_real_escape_string()
或更好的使用准备好的语句- http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.