我正在创建一个应用程序来存储学生记录并编辑和删除它们但是服务器发出了未定义的变量错误(在$ name,$ school_name,$ roll_no,$ result变量行上)虽然变量已定义且我有使用echo检查并且所有变量似乎都工作正常...请帮助我
<form action = 'edit.php?edit_form=<?php echo $edit_id; ?>' method = 'post'>
<table align = "center" width = "500" border = "5">
<tr>
<td colspan = "5"> <h1 align = "center">Update Record</h1> </td>
</tr>
<tr>
<td align = "right">Student Name:</td>
<td> <input type = "text" name = "name" value = "<?php echo $name; ?>"> </td>
</tr>
<tr>
<td align = "right">School Name:</td>
<td> <input type = "text" name = "school" value = "<?php echo $school_name; ?>"> </td>
</tr>
<tr>
<td align = "right">Roll No:</td>
<td> <input type = "text" name = "roll_no" value = "<?php echo $roll_no; ?>"> </td>
</tr>
<tr>
<td align = "right">Result:</td>
<td> <input type = "text" name = "result" value = "<?php echo $result; ?>"> </td>
</tr>
<tr>
<td colspan = "5" align = "center"> <input type = "submit" name = "update" value = "Update Now"> </td>
</tr>
</table>
</form>
答案 0 :(得分:0)
这实际上是有道理的,因为你试图在呈现之前设置渲染表单的变量,因此请求中没有POST数据。
让事情变得有效,你必须从数据库中选择这些数据,例如:
// mysql_connect is deprecated, use mysqli_connect instead
$link = mysqli_connect("localhost", "root", "password");
mysqli_select_db($link, "school");
if (!isset($_GET['edit_form']) || !is_numeric($_GET['edit_form'])) {
// first validate user input from GET request
die('please provide us valid student id');
}
// after successful updating showing confirmation message
if (isset($_GET['show_message'])) {
echo "Data has been updated";
}
$edit_id = $_GET['edit_form'];
//using prepare statement for avoiding SQL injection
$statement = $link->prepare('SELECT student_name, school_name, roll_no, result FROM students WHERE id = ?');
// i because student id should be integer
$statement->bind_param('i', $edit_id);
$statement->execute();
$statement->store_result();
// fill every needy variable from query
$statement->bind_result($name, $school_name, $roll_no, $result);
$statement->fetch();
if (isset($_POST['update'])) {
$name = $_POST['name'];
$school_name = $_POST['school'];
$roll_no = $_POST['roll_no'];
$result = $_POST['result'];
$query = "update students set student_name = ?, school_name = ?, roll_no = ?, result = ? where ID=?";
// once again preparate query for avoiding SQL injection
$statement = $link->prepare($query);
// s for string variable, ssisi - 1st variable is string, 2nd variable is string, 3rd variable is integer ...
$statement->bind_param('ssisi', $name, $school_name, $roll_no, $result, $edit_id);
if ($statement->execute()) {
header("location: index.php?edit_form=$edit_id&show_message=1");
}
} ?>