在PHP中搜索并获得双重结果 [英] Search and get double result in PHP

查看:53
本文介绍了在PHP中搜索并获得双重结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我用来从PHPMyAdmin数据库Mysql中搜索的PHP代码.但是,当我得到结果时,它显示为两倍.我不明白为什么要加倍.如果用于"foreach"循环,那么我将用什么代替它? 请帮我解决代码.

Here is my PHP code which I used to search from database Mysql from PHPMyAdmin. But When I get the result it shows double. I didn't understand why it's double. If it's for 'foreach' loop then what will I use instead of that? Please help me out with the code.

<?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>";
}
}
?>

推荐答案

您正在将查询嵌套在查询中,因此很可能会产生包含所有数据的多个表.您还将执行3次查询(一次使用query()准备了2次).

You are nesting a query within a query, so this will most likely produce multiple tables with all of the data. You are also executing the query 3 times (once prepared an 2 using query()).

代替运行一次查询(prepare()execute()),如果有行,则遍历结果...

Instead run the query once (the prepare() and execute()) and if there are rows, loop over the result...

// 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,但没有使用绑定变量,因此您应该使用...

You are also using prepare and execute, but not using bind variables, so you should really be using...

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();
}

这篇关于在PHP中搜索并获得双重结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆