代码之家  ›  专栏  ›  技术社区  ›  user9449525

在php中使用like%和for each准备搜索

php
  •  0
  • user9449525  · 技术社区  · 7 年前

    我的代码正在发布整个表。相反,它应该只发布所选的like术语$param=“%{$\u POST['search]}%”;。

    资料来源:我主要使用这两篇文章来获取代码: Display a table in a foreach loop with database values & php mysqli prepared statement LIKE

    <table border="2" class="table-responsive" id="employee_table">
    <tr>
    <th>ID</th>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Position</th>
    <th>Date</th>
    <th>Update</th>
    </tr>
    
    <?php 
    if(isset($_POST['search'])) {
    echo "Search Successful!";
    
     $stmt = $con->prepare("SELECT * FROM employees WHERE first_name LIKE ? OR last_name LIKE ?"); 
    $param='%'.$_POST['search'].'%';
    $stmt->bind_param('ss', $param, $param);
    $stmt->execute();
    
    
    $result = $stmt->get_result();
    $i = 0;
    while ($row = $result->fetch_array(MYSQLI_NUM)) {
      foreach ($row as $r) {
          $i++;
        echo '<td> '.$r.'</td>';
     if($i % 6==0){
          echo '</tr><tr>';
       }}}
    }
    ?>
    </tr>
    </table>
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Jirka Hrazdil    7 年前

    首先,您必须更改查询以在中搜索 first_name last_name (原始查询将返回所有行,其中 first\u名称 计算结果为true(基本上是任何非空字符串)。然后必须绑定参数两次:

    $stmt = $con->prepare("SELECT * FROM employees WHERE first_name LIKE ? OR last_name LIKE ?"); 
    $param='%'.$_POST['search'].'%';
    $stmt->bind_param('ss', $param, $param);