MySQL搜索的不规则行为

时间:2015-07-23 07:07:48

标签: php mysql

有时会有匹配,有时则没有;即使我直接从数据库中复制一个值,也不总能找到它。

这是代码:

if (isset($_POST['name_query'])){
    $_name=$_POST['name_query'];
    $new_name=filter_var($_name, FILTER_SANITIZE_STRING);
    $sql="SELECT  client_id, id_num, name, surname FROM clients
          WHERE name = ' $new_name' " ;
    //$new_string = filter_var($string, FILTER_SANITIZE_STRING);

    //-run  the query against the mysql query function 
    $result=mysql_query($sql);
    //error handling
    if($result === FALSE) { 
        die(mysql_error()); 
    }
    echo "<tr>", "</td>","<td>","<h2 style='color:red'>Search Results</h2>","</td>","</tr>";    
    //-create  while loop and loop through result set 
    while($row=mysql_fetch_array($result)) { 
        $id4= $row['client_id'];
        $id_num=$row['id_num']; 
        $name=$row['name']; 
        $surname=$row['surname'];   

        //-display the result of the array............ trim($str,"Hed!");
        if ( $name != '') {
            echo "<tr>", "<td>", 
                 "<a  href=\"display_row.php?client_id=$id4 \">",
                 $id_num, "   " , $name , "    ", $surname,"</a>",
                 "</td>","</tr>";
        }
    }                
}

1 个答案:

答案 0 :(得分:0)

您的值(' $new_name')中有一个冗余空格。你应该

$sql="SELECT client_id, id_num, name, surname FROM clients WHERE name = '$new_name';

强制性评论:
在SQL查询中使用字符串替换是一种不好的做法,使您的代码容易受到SQL注入攻击。请考虑改为使用prepared statements