首页 > 解决方案 > AJAX 给出的结果与 MySQL 不同

问题描述

我在处理 AJAX 结果时遇到了问题。我从 MySQL 的查询中得到了结果,但 AJAX 的响应不同。我将查询等同于 MySQL 和 AJAX。查询将仅显示1 行或根本不显示。你能告诉我哪里错了吗?

这是查询

SELECT a.id_pendaftaran, l.nama_layanan, p2.asal_perusahaan, a.status from
 antrian a JOIN pengunjung p2 ON a.id_pendaftaran = p2.id_pengunjung JOIN 
layanan l ON a.id_layanan = l.id_layanan WHERE a.id_pendaftaran = 'gmFhJd2t0N'

然后这是 AJAX

   $('.cekbutton').click(function(e){
        var id = $('#id_pendaftaran').val();
            e.preventDefault(); 
            $.ajax({
                url:"ajax.php",
                type:"GET",
                data : "id="+id,
                success : function(result) {
                    console.log(result);
                    var datanew = JSON.parse(result);
                    $('#layanan').val(datanew.layanan);
                    $('#nama_perusahaan').val(datanew.nama);
                    $('#status').val(datanew.status);
                    $('#layanan').prop('disabled', true);
                    $('#nama_perusahaan').prop('disabled', true);
                    $('#status').prop('disabled', true);
                }
            });
        });
<?php

    include "../connection.php";

    $q = mysqli_real_escape_string($koneksi, $_GET['id']);

    $query = mysqli_query($koneksi, "SELECT a.id_pendaftaran, l.nama_layanan,
 p2.asal_perusahaan, a.status from antrian a JOIN pengunjung p2 
ON a.id_pendaftaran = p2.id_pengunjung JOIN layanan l ON a.id_layanan = l.id_layanan 
WHERE a.id_pendaftaran = '".$q."'");
    if (mysqli_num_rows($query) == 1) {
        $row = mysqli_fetch_array($query);

        $nama = $row['asal_perusahaan'];
        $layanan = $row['nama_layanan'];
        $status = $row['status'];

        $myObj = array('hasil' => true, 'nama' => $nama, 'layanan' => $layanan, 'status' => $status);
    }
    else {
        $myObj = array('hasil' => false, 'nama' => "-", 'layanan' => "Belum terdaftar", 'status' => "-");
    }

    $myJSON = json_encode($myObj);
    echo $myJSON;
?>

来自 MySQL 的结果

id_pendaftaran | nama_layanan  | asal_perusahaan | status |
gmFhJd2t0N     | Certification | ABC             | Waiting |

这来自浏览器控制台

{"hasil":false,"nama":"-","layanan":"Belum terdaftar","status":"-"}

如果我改变这个等式(mysqli_num_rows($query) == 1)而不是这个,结果将是:

{"hasil":true,"nama":null,"layanan":null,"status":null}

标签: phpmysqlajaxmysqli

解决方案


也许您的查询返回不止一行?if (mysqli_num_rows($query) == 1)


推荐阅读