使用类似%和php中的每个准备搜索

时间:2018-03-06 12:05:50

标签: php

我的代码是发布整个表格。相反,它应该只发布所选的类似术语..... $ param ="%{$ _ 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 个答案:

答案 0 :(得分:0)

首先,您必须将查询更改为在first_namelast_name中搜索(您的原始查询将返回first_name评估为true的所有行 - essentialy任何非空字符串)。然后你必须绑定参数两次:

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