Good work with JSON



  • I wanted to make sure all the news from the database was dropped to json-massis, and then I'd take the whole casket where I wanted to use js. News have an idy, name and content. Show me how you can do this? I would like a format like: 1{'test', 'desc'},2{'test', 'desc'},3{'test', 'desc'},1{'test', 'desc'}♪ It's naturally not like me but json.

    Thanks for the answers, I'm probably in the code with a banal error, but I'm not gonna understand where it comes from.

    <?php
    $main = new PDO('mysql:host=localhost;dbname=world_project', 'world', 'yan6dw');
    $result = $db->query("SELECT `id`,`title`,`content` FROM `News` LIMIT 10");
    while ($row = $result->fetch())
    {
    $news = [
      $row['id'] => [
        'title' => $row['title'],
        'text' => $row['content']
      ]];
    }
    die ($news);
    ?>
    

    введите сюда описание изображения

    Fatal error: Uncaught Error: Call to a member function query() on null in /home/world/w-0rld.ru/connect.php:3 Stack trace: #0 /home/world/w-0rld.world/functions.php(2): include_once() /mainhome/world/w-0rld.ru/

    How do I fix it?


  • QA Engineer

    Get in the PHP an associated mass of the right species.

    $result = array(
      $news_id => array(
        'text' => $news_text,
        'desc' => $news_desc,
      ),
      // ...
    )
    

    Take him to JSON:

    $json_data = json_encode( $result);
    

    And give it to the browser or right on the page as part of the violin:

    <html>
    ...
    <script>
        var news = <?php echo $json_data ?>;
        // и теперь можно получать новость:
        var html='', id;
        for( id in news) {
            html += '<div><h4>' + news[id].text + '</h4>';
            html += '<p>' + news[id].desc + '</p></div>';
        }
        document.getElementById('b-news').innerHTML = html;
    </script>
    

    Or have a violin from ajax-request get data from a separate url on the server. Then add a hundred title to the answer:

    <?php
    // ...
    header('Content-Type: application/json');
    echo json_data;
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2