douya2007 2017-04-07 15:48
浏览 87
已采纳

PHP AJAX通知,如果MySQL查询没有返回任何行

Situation

I've got a working script that sends an ajax request to get_code.php. This script is run from the main page - index.php. The get_code.php script queries my MySQL DB for a row and then sends back the data to index.php.

Current code

jQuery in index.php

<script type="text/javascript">
$("#CMTCode").click(function(){
    var cde = $("#cmtcodeinput").val();
        $.ajax({
            method:'POST',
            url:'get_code.php',
            data: {va_code:cde},
            dataType: 'json',
            success: function(output_string){
                    $('#rtable').append(output_string);
                    $("#cmtcodeinput").val('');
                    var prc = $(".price:last");
                    prc.focus();
            }
        });
});    
</script>

PHP script get_code.php

<?php
include('dbc.php');
$code = $_POST['va_code'];
$cq = mysql_query("SELECT * FROM variants where va_code='$code'")or die(mysql_error());
  if(!$cq){
mysql_close();
echo json_encode('There was an error running the query: ' . mysql_error());
  }elseif(!mysql_num_rows($cq)){
mysql_close();
echo json_encode('No results returned');
  }else{
$output_string = '';
$output_string .= '<tr>';
while($row = mysql_fetch_assoc($cq))
{        
     $output_string .= '<td>'.$row['cmtcost'].'</td>';
//etc. etc. lots more output here
}
     $output_string .= '</tr>';
}
mysql_close();
echo json_encode($output_string);
?>

Problem

However, if no results are found for the query, nothing is returned on the page to notify the user. Ideally I'd like to open a modal, or display a div in which I can use the data the user input. I just can't work out for the life of me how to check if $cq returns no results, and if so then to display something on index.php like a notification saying 'Your code was not found'.

Appreciative of any help

  • 写回答

1条回答 默认 最新

  • dongsanhu4784 2017-04-07 15:58
    关注

    You could return a result flag. This is a good logic and easy to understand.

    If no row was found :

    die(json_encode(['result' => false, 'error' => 'No code was found']));
    

    If some code found :

    die(json_encode(['result' => true, 'output' => $output_string]));
    

    And in js :

    ...
    success: function(data){
        if (!data.result) {
            alert(data.error);
        } else {
            $('#rtable').append(data.output);
            $("#cmtcodeinput").val('');
            var prc = $(".price:last");
            prc.focus();
        }
    }
    ...
    

    Hope it helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错