从PHP和MYSQL生成JSON代码

时间:2018-01-17 08:28:23

标签: php mysql json

嗨朋友们在这里遇到麻烦,我想为json格式的通知生成此代码,所以我可以转换为html但我收到此错误: 注意:未定义的变量:第70行的C:\ xampp \ htdocs \ futbolextensive.co.ke \ notifications_controller.php中的result_array { “结果”:空} 这是我的代码

<?php
     //Select all notifications for a given user_id and return in JSON format
       $sql = "select * from notifications";
       $res = mysqli_query($con,$sql);
       $result = array();
       while($row = mysqli_fetch_array($res)) 
        {
           array_push($result,array('id'=>$row[0],'creation_date_time'=>$row[1],
           'view_date_time'=>$row[2],'user_id'=>$row[3],'notification_text'=>$row[4],'is_viewed'=>$row[5]));
        }
        echo json_encode(compact('result'));
        //Here you can format all notifications into well-organized HTML code just like in order to present in nice way
        //it is being returned in JSON format
        exit;
?>

这里是输出html的javascript但是仍然返回json格式

<script>
function show_notifications()
{
  //user_id = 1 First User's Id
  //command = FETCH_NOTIFICATIONS
  var show_notifications_url = "notifications_controller.php?command=FETCH_NOTIFICATIONS&user_id=15";
       $( document ).ready(function() 
         {
            $.ajax({
                     url: show_notifications_url,
                     cache: false,
                     success: function(html) 
                      {
                          $("#notification_results").append(html);
                          //Change the content of the DIV in User's profile page where notifications will be displayed
                      } 
                   }); 
         });
} //function show_notifications

function startTimer() 
   {
      //call show_notifications
      show_notifications();
      //then start interval
      setInterval(show_notifications, 30000); //Refresh after 30 seconds
   } //function startTimer()
</script>

//这是json中的结果

{"result":[{"id":"7","creation_date_time":"2018:01:16 07:05:46","view_date_time":"2018:01:16 07:05:46","user_id":"3","notification_text":"Hello","is_viewed":"NO\""},{"id":"8","creation_date_time":"2018:01:16 11:58:03","view_date_time":"2018:01:16 11:58:03","user_id":"1","notification_text":"felix khalawa liked your post","is_viewed":"NO"},

1 个答案:

答案 0 :(得分:0)

您应该将$ result_array更改为$ result。

或者你可以像这样使用契约:

<?php
echo json_encode(compact('result'));
?>