这是我用来从PHPMyAdmin从数据库Mysql搜索的PHP代码。但是,当我得到结果时,它显示为两倍。我不明白为什么要加倍。如果用于“ foreach”循环,那么我将用它代替什么? 请帮我解决代码。
<?Php
?>
<html>
<head>
<style>
@media print {
#printPageButton {
display: none;
}
#another {
display: none;
}
}
.border {
border-style: double;
border-color: blue;
}
</style>
<title>Demo of Search Keyword using PHP and MySQL</title>
</head>
<body>
<?Php
error_reporting(0);
include "config_1.php";
$todo=$_POST['todo'];
$search_text=$_POST['search_text'];
if(strlen($serch_text) > 0){
if(!ctype_alnum($search_text)){
echo "Data Error";
exit;
}
}
if(isset($todo) and $todo=="search"){
$type=$_POST['type'];
$search_text=ltrim($search_text);
$search_text=rtrim($search_text);
if($type<>"any"){
$query="select * from billbagnan where name='$search_text'";
}
$count=$dbo->prepare($query);
$count->execute();
$no=$count->rowCount();
foreach ($dbo->query($query) as $row){
echo "
<table class='border' style='text-align:center;' width='900'>";
echo "</td><td width='400' valign=top>";
echo " Full records here ";
echo "<table><tr><th>ID</th><th>Name</th><th>Institution</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[instn]</td>
</tr>";
}
echo "</table>";
echo "</td></tr></table>";
}
}
?>
答案 0 :(得分:2)
您正在将查询嵌套在查询中,因此这很可能会产生包含所有数据的多个表。您还将执行3次查询(一次使用query()
准备了2次)。
代替运行一次查询(prepare()
和execute()
),如果有行,则循环搜索结果...
// If there are rows
if ($count->rowCount() > 0 ) {
echo "<table class='border' style='text-align:center;' width='900'>";
echo "</td><td width='400' valign=top>";
echo " Full records here ";
echo "<table><tr><th>ID</th><th>Name</th><th>Institution</th></tr>";
// Loop over rows and display data
while ( $row = $count->fetch(PDO::FETCH_ASSOC)) {
您还使用了prepare and execute,但未使用绑定变量,因此您应该使用...
if($type<>"any"){
$query="select * from billbagnan where name=?";
$count=$dbo->prepare($query);
$count->execute([$search_text]);
}
else {
$query="select * from billbagnan";
$count=$dbo->prepare($query);
$count->execute();
}