通配符SQL搜索php

时间:2014-11-19 20:28:30

标签: php mysql

 <form name="attdate" action="keyword.php" method="post">
      Enter Keyword :<input name = "key">   
      <button  class='btn btn-lg btn-danger' type ="submit"> Search Records</button>

我要做的是使用关键字(通配符)搜索查询我的varchar字段:

我要查询的行中的字段是&#39; hs&#39; &#39; NV&#39; &#39; VSA&#39; 。

我的PHP看起来像这样:

<?php


include 'config.php';

$key = ($_POST['key']);



$key = mysqli_real_escape_string($con,$key);



$sql = "SELECT * FROM handover WHERE hs LIKE "%'.$key.'%"
OR WHERE nv LIKE "%'.$key.'%"
OR WHERE vsa LIKE "%'.$key.'%"";


$result = mysqli_query($con,$sql);

$count=mysqli_num_rows($result);

if($count==0 ){

echo "</br></br></br></br></br></br></br><h2>Handover Details</h2><p> No Matching   

results found</p>";
}
else{
while($row = mysqli_fetch_array($result)) {
echo '</br></br></br></br></br>';

我认为这可能是我放置%的地方。该列不是索引的一部分,这是一个问题吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

更改报价单,在查询的开头和结尾放置单引号,反之亦然。

$sql = 'SELECT * FROM handover WHERE hs LIKE "%'.$key.'%"
OR WHERE nv LIKE "%'.$key.'%"
OR WHERE vsa LIKE "%'.$key.'%"';

您还需要parameterise您的查询,而不是将变量直接注入查询字符串。这将有助于您Prevent SQL Injection!

更新:参数化查询示例:

$mysqli = new mysqli("host", "user", "password", "database");// connection
$key = $_POST['key'];
$query = $mysqli->prepare("SELECT * FROM handover WHERE hs LIKE ? OR WHERE nv LIKE ? OR WHERE vsa LIKE ?"); // note how simple in this case, no quoting problems
$stmt->bind_param("sss", $key, $key, $key); // binding a string which replaces ?, once for each ? (repeats in your case)
$stmt->execute();