那里! 我想要进行数据库搜索并以预先填充的 HTML 表单将结果显示给用户。
我找到了代码中不起作用的确切部分,但我无法理解为什么服务器没有选择 PHP。我正在使用 UwAMP。
为了说明问题,这里是我需要帮助的简短代码片段:
<form id="st_reg" action="" method="POST">
Student Number:
<input type="number" name="s_num" min="1000000" max="3000000" > </br>
<input type="Submit" value="Search">
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['s_num'])){
$errors[] = "You forgot to enter the Student No!";
}
else{
$st_no = trim($_POST['s_num']);
}
if(empty($errors)){
//Open database connection
require('../../connect_to_database/mysql_connect.php');
//Check if the student is already in the database
$query = "SELECT * FROM student WHERE student_no = $st_no";
//Run the query
$result = mysqli_query($db_connection,$query);
if(!$result){
echo "The student does not exist!";
echo"Please <a href='index.html'>go back</a> and choose another action!";
}
elseif($result){
echo "<h2>Student Details:</h2>";
while($row = mysqli_fetch_array($result)){
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> ">
并且 VALUE ATTRIBUTE 中的 PHP 代码实际上没有执行。不要担心 GLOBAL php 标签没有被关闭,因为它们在文件中(我不是那个转储)。
请注意,所有这些代码都位于带有 HTML 代码的 .php 文件内。这只是提交表单后的处理部分。我通过使用单引号进行回显节省了时间,并在需要数据库访问时转义了单引号。我尝试用大括号括住变量,用双引号回显其中的双引号,但这些尝试都没有成功。 这很奇怪,因为我可以在此上下文之外完美地回显 $row['student_no'] 并且运行良好。
我也在这个网站上看过类似的问题。他们很接近,但没有一个人有这样的背景。我愿意接受任何建议以及比这些更好的解决方案。
最佳答案
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> ">
应该看起来像这样:
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="' . (isset($row['student_no']) ? $row['student_no'] : '') . '">
CONTINUATION OF STRING...
关于HTML value 属性内的 PHP 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45177183/