I wanted to do this: all the news from the database to throw in the json-array, and then output all the mess where you want using js. The news has its ID, title and content. Give an example of how all this can be done? I would like a type format: 1{'test', 'desc'},2{'test', 'desc'},3{'test', 'desc'},1{'test', 'desc'} . Naturally not like me, but like json.

Thanks for the answers, I probably have a banal error in the code, but I still do not 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); ?> 

enter image description here

Fatal error: Uncaught Error: Call to a member function query () on null in /home/world/w-0rld.ru/connect.php.l Stack trace: # 0 /home/world/w-0rld.ru/functions .php (2): include_once () # 1 /home/world/w-0rld.ru/index.php(2): include_once ('/ home / world / w-0 ...') # 2 {main} thrown in / home / world / w-0rld.ru/connect.php on line 3

How to fix?

    3 answers 3

    Get in PHP an associative array of the desired type.

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

    Translate it to JSON:

     $json_data = json_encode( $result); 

    And give it to the browser or directly in the body of the page as part of the script:

     <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 let the script from the page receive ajax-request data from a separate url on the server. Then add acc. response header:

     <?php // ... header('Content-Type: application/json'); echo json_data; 
    • I did not see your answer when I wrote my :) - Stanislav

    If you can get an array of news, then making it json is not difficult:

     $news = [ 15 => [ 'title' => 'Title 1', 'text' => 'text 15' ], 18 => [ 'title' => 'Title 2', 'text' => 'text 18' ] ]; $json = json_encode($news); 
       function json('запрос') { /* Соединение с БД */ // Получение и возврат результатов $result = $db->query('запрос'); $List = array(); $i = 0; while ($row = $result->fetch()) { $List[$i]['id'] = $row['id']; $List[$i]['news'] = $row['news']; $List[$i]['title'] = $row['title']; $List[$i]['description'] = $row['description']; $i++; } return $List; } 
      • four
        Where is JSON, besides the function name? - Sergiks