从数据库(PHP MySQL)中搜索和显示结果不适合 html 中的表格

Posted

技术标签:

【中文标题】从数据库(PHP MySQL)中搜索和显示结果不适合 html 中的表格【英文标题】:Search and Display Results From Database (PHP MySQL) not Fitting into a Table in html 【发布时间】:2021-01-07 05:41:22 【问题描述】:

我的代码按照我的意愿工作,原理是在表格中进行搜索,根据用户输入的内容,我将在 html 页面中显示已经设计好的表格中的属性。为了更好地理解,我将放一张搜索结果的图片。

output of the search

由于这段代码有 printf 我不知道什么适合将数据输出到我的表中,我选择了 12 个属性并且我正在使用 ajax 和 javascript

index.html(只是其中的一部分)

<br><br>
<!-- Search box. -->
    <form method="post" action="index.php">
    <input type="text" id="search" name="search" required placeholder="Search for an item" /><input type="submit" value="LOAD"/>
    <br></form>

    <b>Ex: </b><i>Bread, Milk, Egg, etc or SKU</i>
    <br />
    <!-- Suggestions will be displayed in below div. -->
    <div id="display"></div>


<table id="itemsTable"> <tr>    <th>Quantity</th> 
                                <th>Item</th> 
                                <th>SKU</th> 
                                <th>Item Name</th> 
                                <th>Item Price</th> 
                                <th>Subtotal</th> 
                                <th>Cartons Scanned</th> 
                                <th>Individually Scanned</th> 
                                <th>Current Inventory</th> 
                                <th>Location Selected</th> 
                                <th>Image</th> 
                                <th>Edit</th>
                        </tr><tr><td>
              <?php
    if (isset($_POST['search'])) 
      // SEARCH FOR ITEM NAME
      require "2-search.php";

      // DISPLAY RESULTS
      if (count($results) > 0) 
        foreach ($results as $r) 
          printf("<div>%s - %s - %s - %s - %s - %s - %s - %s - %s - %s - %s- %s</div>", $r['quantity'], $r['item'], $r['sku'], $r['item_name'], $r['item_price'], $r['subtotal'], $r['cartons_scanned'], $r['ind_scanned'], $r['cur_inventory'], $r['location_sel'], $r['image'], $r['edit']);
        
       else 
        echo "No results found";
      
    
    ?>
           </td></tr></table> 
<br><br><br>

2-search.php

<?php
// (1) DATABASE CONFIG
// ! CHANGE THESE TO YOUR OWN !
define('DB_HOST', 'localhost');
define('DB_NAME', 'create_order_db');
define('DB_CHARSET', 'utf8');
define('DB_USER', 'root');
define('DB_PASSWORD', '');

// (2) 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,
    PDO::ATTR_EMULATE_PREPARES => false ]
  );
 catch (Exception $ex) 
  die($ex->getMessage());


// (3) SEARCH
$stmt = $pdo->prepare("SELECT quantity,item,sku,item_name,item_price,subtotal,cartons_scanned,ind_scanned,cur_inventory,location_sel,image,edit FROM `item_new` WHERE `item_name` LIKE ? OR `sku` LIKE ?");
$stmt->execute(["%" . $_POST['search'] . "%", "%" . $_POST['search'] . "%"]);
$results = $stmt->fetchAll();
if (isset($_POST['ajax']))  echo json_encode($results); 

3-ajax 搜索

<!DOCTYPE html>
<html>
  <head>
    <title>
      AJAX Search Example
    </title>
    <script>
      function fetch() 
        // GET SEARCH TERM
        var data = new FormData();
        data.append('search', document.getElementById("search").value);
        data.append('ajax', 1);

        // AJAX SEARCH REQUEST
        var xhr = new XMLHttpRequest();
        xhr.open('POST', "2-search.php", true);
        xhr.onload = function () 
          if (this.status==200) 
            var results = JSON.parse(this.response),
                wrapper = document.getElementById("results");
            wrapper.innerHTML = "";
            if (results.length > 0) 
              for(var res of results) 
                var line = document.createElement("div");
                wrapper.appendChild(line);
                line.innerHTML = res['quantity'] + " - " + res['item'] + " - " + res['sku'] + " - " + res['item_name'] + " - " + res['item_price'] + " - " + res['subtotal'] + " - " + res['cartons_scanned'] + " - " + res['ind_scanned'] + " - " + res['cur_inventory'] + " - " + res['location_sel'] + " - " + res['image'] + " - " + res['edit'];
                wrapper.appendChild(line);
              
             else 
              wrapper.innerHTML = "No results found";
            
           else 
            alert("ERROR LOADING FILE!");
          
        ;
        xhr.send(data);
        return false;
      
    </script>
  </head>
  <body>
    <!-- [SEARCH FORM] -->
    <form onsubmit="return fetch();">
      <h1>SEARCH FOR USERS</h1>
      <input type="text" id="search" required/>
      <input type="submit" value="Search"/>
    </form>

    <!-- [SEARCH RESULTS] -->
    <div id="results"></div>
  </body>
</html>

【问题讨论】:

为什么使用printf 而不是直接echo 与表? 只是一个建议。 Datatable 是一个非常好的制作表格的插件。对不起,我不能回答,我还是菜鸟。 datatables.net 【参考方案1】:

感谢 cmets,感谢 @simone 我能够回答我自己的问题。

<table id="itemsTable"> <tr>    <th>Quantity</th> 
                                <th>Item</th> 
                                <th>SKU</th> 
                                <th>Item Name</th> 
                                <th>Item Price</th> 
                                <th>Subtotal</th> 
                                <th>Cartons Scanned</th> 
                                <th>Individually Scanned</th> 
                                <th>Current Inventory</th> 
                                <th>Location Selected</th> 
                                <th>Image</th> 
                                <th>Edit</th>
                        </tr>
              <?php
    if (isset($_POST['search'])) 
      // SEARCH FOR ITEM NAME
      require "2-search.php";

      // DISPLAY RESULTS
      if (count($results) > 0) 
        foreach ($results as $r) 
          echo "<tr>";
          echo "<td>" . $r['quantity'] . "</td>";
          echo "<td>" . $r['item'] . "</td>";
          echo "<td>" . $r['sku'] . "</td>";
          echo "<td>" . $r['item_name'] . "</td>";
          echo "<td>" . $r['item_price'] . "</td>";
          echo "<td>" . $r['subtotal'] . "</td>";
          echo "<td>" . $r['cartons_scanned'] . "</td>";
          echo "<td>" . $r['ind_scanned'] . "</td>";
          echo "<td>" . $r['cur_inventory'] . "</td>";
          echo "<td>" . $r['location_sel'] . "</td>";
          echo "<td>" . $r['image'] . "</td>";
          echo "<td>" . $r['edit'] . "</td>";
          echo "</tr>";
        
       else 
        echo "No results found";
      
    
    ?>
           </table> 

【讨论】:

以上是关于从数据库(PHP MySQL)中搜索和显示结果不适合 html 中的表格的主要内容,如果未能解决你的问题,请参考以下文章

在 PHP MySQL 搜索中未找到结果时显示消息

PHP MySQL:搜索数据库中的字符串(在数组中)丢失的结果

使用 php mysql 按半径搜索经纬度数据库

搜索结果转换中的多个索引不适用于Kentico

如何按距离从数据库中排序 php 结果

PHP/MySQL:突出显示“SOUNDS LIKE”查询结果