【问题标题】:GENERATE JSON CODE FROM PHP AND MYSQL从 PHP 和 MYSQL 生成 JSON 代码
【发布时间】:2018-01-17 08:28:22
【问题描述】:

嗨朋友们在这里遇到了麻烦,我想为 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"},

【问题讨论】:

标签: php mysql json


【解决方案1】:

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

或者你可以像这样使用紧凑:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-22
    • 2014-10-19
    • 2010-09-18
    • 1970-01-01
    • 2012-06-03
    • 2018-06-15
    • 2010-11-20
    • 1970-01-01
    相关资源
    最近更新 更多