我有一个用户输入数据的表单,例如AXZAA QS1QS。该数据已发布到我的 PHP 脚本中。 PHP 脚本连接到 MYSQL 数据库,该数据库目前包含 2 条记录。
这个想法是 PHP 脚本将获取输入并将其与数据库中的记录进行比较。如果记录存在,它们会显示在网页上的表格中,否则会显示错误消息。
我的 PHP 脚本存在许多问题,并且已多次修改我的脚本。然而,我遇到的最大问题是:
当表单第一次出现时,消息记录不存在会出现两次,这是在用户输入任何数据并且第一次看到表单之前。见下图。
输入数据后(当 PHP 脚本部分正常工作时),如果存在匹配项,即存在记录,以及表中的记录,我将收到一条错误消息,告诉我未找到记录。为了看看是否可以解决问题,我添加了代码来告诉我找不到哪些记录,找不到的记录是已找到的记录以及数据库中我没有查找的其他记录。我知道 PHP 脚本中的 SQL 查询告诉脚本从数据库中获取所有内容,但是,我本以为 if 语句可以解决问题。
很抱歉写了这么长的问题,希望它不会造成困惑。
enter code here
<?php
//Connect to the database connection file
require 'databaseconnection.php';
$searchBar=(isset($_POST['searchBar']) ? $_POST['searchBar'] :null);
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
?>
最佳答案
在 if 语句之后分配 $searchbar 不是更好吗
`<?php
//Connect to the database connection file
require 'databaseconnection.php';
if(isset($_POST['searchBar']))
{
$searchbar = $_POST['searchBar'];
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
}
else{
echo "<p>Please enter a search term</p>";
}
?>
然后,您可以在该“if”语句中执行 MySQL 查询,而不是假设有一个值来执行它
关于php - 正在显示不需要的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42327467/