【问题标题】:SQL Search Query show same results many times although it is only single time in my databaseSQL 搜索查询多次显示相同的结果,尽管它在我的数据库中只有一次
【发布时间】:2022-01-03 13:16:55
【问题描述】:

项目- 数据库名称-test2

我的数据库中有 2 个表

table1 包含

Id  Name    Mobile  Email   
17  name1   1111    name1@test  
18  name2   2222    name2@test  
28  name3   3333    name3@test  

table2 包含

Sr. Id  Paymobile   Month   Amount  Date    
1   28  3333        Jan     200     2021-01-06  
2   28  3333        Feb     400     2021-02-06  
3   28  3333        Apr     600     2021-04-08  
4   17  1111        Mar     400     2021-03-05  
6   18  2222        Aug     100     2021-08-27  
7   17  1111        Jun     600     2021-06-21  

table1 有单一且唯一的记录, table2 已包含付款历史记录,因此 id 和 mobile 有多次。

我想要什么 如果我搜索手机或电子邮件 ID,那么它也会在两个表格中给出结果 像第一个表显示 ID、姓名、手机、来自 table1 的电子邮件 和 第 2 个表显示表 2 中的月份、金额、日期。 一切都很好,但是下面提到了一个问题。

问题 当我搜索手机号码时。 3333 或 2222 在我的网页中,然后它在两个表中显示两个结果,就像我想要的一样 table1 显示 Id,Name,Mobile,来自 table1 的电子邮件 和 第 2 个表显示表 2 中的月份、金额、日期。

但主要问题是它会多次显示 Id、Name、Mobile、Email,尽管它在我的数据库中只有一条记录。喜欢enter image description here

我的配置

1-form.php

<!DOCTYPE html>
<html>
  <body>
    <!-- (A) SEARCH FORM -->
    <form method="post" action="1-form.php">
      <h1>SEARCH FOR USERS</h1>
      <input type="text" name="search" required/>
      <input type="submit" value="Search"/>
    </form>
 
    <table>
    <style>
        table { font-family: arial, sans-serif;
                border-collapse: collapse;
                width: 100%;
    }
    td, th {border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
    }

    tr:nth-child(even) {
        background-color: #dddddd;
    }
    </style>
        <tr>
          <th>Id</th>
          <th>Name</th>
          <th>Mobile</th>
          <th>Email</th>
        </tr>
<?php
// (B2) DISPLAY RESULTS 
?>
<?php
// (B) PROCESS SEARCH WHEN FORM SUBMITTED
if (isset($_POST["search"])) {
    // (B1) SEARCH FOR USERS
    require "2-search.php";
?>
  
<?php
    // (B2) DISPLAY RESULTS 
    if(isset($_POST) && array_key_exists('search',$_POST)) {
        if (count($results) > 0) { foreach ($results as $r) {
?>  
            <tr>  
                <td> <?php echo $r['Id'] ;?> </td>                
                <td> <?php echo $r['Name'] ;?> </td>
                <td> <?php echo $r['Mobile'] ;?> </td>
                <td> <?php echo $r['Email'] ;?> </td>
            </tr>
<?php
        }
    }
} else { 
    echo "No results found"; }
}
?>


  </table>
  <p>
    <table>
        <tr>
            <th>Month</th>
            <th>Amount</th>
            <th>Date</th>
        </tr>
<?php
// (B2) DISPLAY RESULTS
if (count($results) > 0) { 
    foreach ($results as $r) {
?>  
        <tr>                  
            <td> <?php echo $r['Month'] ;?> </td>
            <td> <?php echo $r['Amount'] ;?> </td>
            <td> <?php echo $r['Date'] ;?> </td>
        </tr>
<?php
    }
} else { 
    echo "No results found"; 
}
?>
</table>
</html>

2-search.php

<?php
// (A) DATABASE CONFIG - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test2");
define("DB_CHARSET", "utf8");
define("DB_USER", "root");
define("DB_PASSWORD", "");

// (B) CONNECT TO DATABASE
try {
    $pdo = new PDO(
        "mysql:host=".DB_HOST.";charset=".DB_CHARSET.";dbname=".DB_NAME,
        DB_USER, DB_PASSWORD, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (Exception $ex) { 
    exit($ex->getMessage()); 
}

// (C) SEARCH
$stmt = $pdo->prepare("SELECT table1.*, table2.* 
                        FROM table1 
                        INNER JOIN table2 ON table1.Id = table2.Id 
                        WHERE `Name` LIKE ? OR `Mobile` LIKE ?");
$stmt->execute(["%".$_POST["search"]."%", "%".$_POST["search"]."%"]);
$results = $stmt->fetchAll();
if (isset($_POST["ajax"])) { 
    echo json_encode($results); 
} 

【问题讨论】:

  • 良好的代码缩进将帮助我们阅读代码,更重要的是它将帮助您调试您的代码 Take a quick look at a coding standard 为您自己的利益。您可能会被要求在几周/几个月内修改此代码,最后您会感谢我的。
  • 我一定会看看好的代码缩进。谢谢你给我一个建议。

标签: php html mysql database


【解决方案1】:

INNER JOIN 将显示两个表的所有匹配行。如果您点击 ID 28,它在 table1 中出现了 1 次,但在 table2 中出现了 3 次,您将总共获得 3 行。

您可以在查询中添加 GROUP BY Id 或进行 2 个查询 - 每个表一个 - 而不是 1 个使用 INNER JOIN 的查询。

【讨论】:

  • 阅读您的答案后,我尝试使用 Group BY Id 进行操作,但此后我无法从 table2 中为 Id 28 获取所有付款记录。目前我总共有 3 条 id 28 记录,这三条记录都有唯一的付款月份、金额和日期。月份、金额、日期这三个记录都是必填项。
  • 还有一个我不知道如何为一个项目进行 2 次查询。
【解决方案2】:

您可以使用关键字DISTINCT

SELECT DISTINCT table1.*, table2.* 
FROM table1 
INNER JOIN table2 ON table1.Id = table2.Id 
WHERE `Name` LIKE ? OR `Mobile` LIKE ?

【讨论】:

  • 我已经在我的代码中尝试了DISTINCT 但不起作用它也多次显示相同的记录。可能是因为我做了一个INNER JOIN 所以它在这里不起作用。
【解决方案3】:

借助 stack over flow 和 w3school 混合多个步骤和方法。

现在我的新配置在下面列出

1-form.php

<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}

td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}

tr:nth-child(even) {
background-color: #dddddd;
}
</style>

<!DOCTYPE html>
<html>
  <body>
    <!-- (A) SEARCH FORM -->
    <form method="post" action="1-form.php">
      <h1>SEARCH FOR USERS</h1>
      <input type="text" name="search" required/>
      <input type="submit" value="Search"/>
    </form>

    <?php
    // (B) PROCESS SEARCH WHEN FORM SUBMITTED
    if (isset($_POST["search"])) {
      // (B1) SEARCH FOR USERS
      require "2-search.php";
      ?>

      <table>

        <tr>
      
          <th>Id</th>
          <th>Name</th>
          <th>Mobile</th>
          <th>Email</th>
        </tr>
        <?php
      // (B2) DISPLAY RESULTS
      if (count($results) > 0) { foreach ($results as $r) {
      ?>  
      
      <tr>                  
                <td> <?php echo $r['Id'] ;?> </td>
                <td> <?php echo $r['Name'] ;?> </td>
                <td> <?php echo $r['Mobile'] ;?> </td>
        <td> <?php echo $r['Email'] ;?> </td>
                </tr>
        <?php

        
      }} else { echo "No results found"; }
    }
    ?>
    </table>







<p>
  Billing Details
  <p>

<?php
    // (B) PROCESS SEARCH WHEN FORM SUBMITTED
    if (isset($_POST["search"])) {
      // (B1) SEARCH FOR USERS
      
      ?>

      <table>

        <tr>
      
          <th>Id</th>
          <th>Name</th>
          <th>Mobile</th>
          <th>Email</th>
        </tr>
        <?php
      // (B2) DISPLAY RESULTS
      if (count($results2) > 0) { foreach ($results2 as $r2) {
      ?>  
      
      <tr>                  
                <td> <?php echo $r2['Id'] ;?> </td>
                <td> <?php echo $r2['Month'] ;?> </td>
                <td> <?php echo $r2['Amount'] ;?> </td>
        <td> <?php echo $r2['Date'] ;?> </td>
                </tr>
        <?php

        
      }} else { echo "No results found"; }
    }
    
    ?>
</table>


  </body>
</html>

2-search.php

<?php
// (A) DATABASE CONFIG - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test2");
define("DB_CHARSET", "utf8");
define("DB_USER", "root");
define("DB_PASSWORD", "");

// (B) CONNECT TO DATABASE
try {
  $pdo = new PDO(
    "mysql:host=".DB_HOST.";charset=".DB_CHARSET.";dbname=".DB_NAME,
    DB_USER, DB_PASSWORD, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]
  );
} catch (Exception $ex) { exit($ex->getMessage()); }

// (C) SEARCH
$stmt = $pdo->prepare("SELECT * FROM `table1` WHERE `Id` LIKE ? OR `Mobile` LIKE ?");
$stmt->execute(["%".$_POST["search"]."%", "%".$_POST["search"]."%"]);
$results = $stmt->fetchAll();
if (isset($_POST["ajax"])) { echo json_encode($results); }

$pdo->connection = null;
$pdo=null;





try {
  $pdo2 = new PDO(
    "mysql:host=".DB_HOST.";charset=".DB_CHARSET.";dbname=".DB_NAME,
    DB_USER, DB_PASSWORD, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]
  );
} catch (Exception $ex) { exit($ex->getMessage()); }

// (C) SEARCH
$stmt2 = $pdo2->prepare("SELECT * FROM `table2` WHERE `Id` LIKE ? OR `Paymobile` LIKE ?");
$stmt2->execute(["%".$_POST["search"]."%", "%".$_POST["search"]."%"]);
$results2 = $stmt2->fetchAll();
if (isset($_POST["ajax"])) { echo json_encode($results2); }

$pdo2->connection = null;
$pdo2=null;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 2014-04-21
    • 2015-06-20
    相关资源
    最近更新 更多