MySQL:选择LIKE无法正常工作

时间:2014-09-01 22:49:25

标签: php mysql

如果名称存在,我会使用此代码搜索数据库:

<?php
$name = $_POST['name'];

$get_search_results_q= "SELECT * FROM `users`.`info` WHERE `info`.`fullname` LIKE '%$name%' ";
$get_search_results_run=mysql_query($get_search_results_q); 
if($get_search_results_run==0){
    echo "No results were found";
}else{
    while($rows = mysql_fetch_assoc($get_search_results_run,MYSQL_NUM)){
        $com_array[] = $rows[3];
    }
    echo json_encode($com_array);
}

?>


当我输入DB中存在的名称时,它工作正常。
但是当我键入不存在的内容时,不会返回任何内容 这是显示数据的jQuery AJAX代码:

.done(function(data) {
                var result = eval(data);
                if(!result){
                    $(".results").empty();
                    $(".results").append('<div class="horizontal result_element">'+result+'</div>');
                    $("#search_result_box").show();
                }else{
                    $(".results").empty();
                    for (var i = 0; i < result.length; i++) {
                        $(".results").append('<div class="horizontal result_element"><div class="result_photo"></div><div class="result_data">'+result[i]+'</div></div>');
                    }
                    $("#search_result_box").show();
                }
                });

我尝试了很多东西,比如在jQuery和mysql_query结果上显示数据,但没有任何反应。

1 个答案:

答案 0 :(得分:1)

试试这个

$total_rows = mysql_num_rows($get_search_results_run);
if(!$total_rows){
   echo "No results were found";
}else{
   while($rows = mysql_fetch_assoc($get_search_results_run,MYSQL_NUM)){
      $com_array[] = $rows[3];
   }
   echo json_encode($com_array);
}

修改

我认为因为您发送的错误类型不是对象json格式,请尝试:

$name = $_POST['name'];

$get_search_results_q= "SELECT * FROM `users`.`info` WHERE `info`.`fullname` LIKE '%$name%' ";
// I missing this before
$get_search_results_run = mysql_query($get_search_results_q);
$total_rows = mysql_num_rows($get_search_results_run);
if(!$total_rows){
   $error['message_message'] = "No results were found";
   echo json_encode($error);
}else{
   while($rows = mysql_fetch_assoc($get_search_results_run,MYSQL_NUM)){
      $com_array[] = $rows[3];
   }
   echo json_encode($com_array);
}

.done(function(data) {
                var result = eval(data);
                if(result.error){
                    $(".results").empty();
                    $(".results").append('<div class="horizontal result_element">'+result.error+'</div>');
                    $("#search_result_box").show();
                }else{
                    $(".results").empty();
                    for (var i = 0; i < result.length; i++) {
                        $(".results").append('<div class="horizontal result_element"><div class="result_photo"></div><div class="result_data">'+result[i]+'</div></div>');
                    }
                    $("#search_result_box").show();
                }
                });