How do i save the data from a MongoDB into my php file as an array and then do a redirect?

81 views Asked by At

Aight so basically I'm working on a News site as a project and in the homepage (index.php) i need to show the articles on the main page that are saved in a document on the mongodb database for showing it basically i have this function

    $ARR_articles = article_recordset();
    
    $STR_article = NULL;
    
    foreach($ARR_articles as $index => $article){
        $STR_article .= get_article_item_html(
            $img_path = "img/article/".$index.".jpg", 
            $title = $article["title"], 
            $description = $article["content"]
        );
    }

while the article recordset function is from another functions file which first had various arrays as recordset for the articles while now it's like this

function article_recordset(){
   

require 'vendor/autoload.php';

$client = new MongoDB\Client("mongodb://localhost:27017");

$SiteArticles = $client->SiteArticles;
$articoli=$SiteArticles->Articles;
$cursor = $articoli->find();

    foreach ($cursor as $articolo) {
        $recordset = array(
                "title" => $articolo["title"],
                "description" => $articolo["content"],
                "article" => "",
        );

    }
}    

i try to save the mongodb data as an array so i can show it on the main index using it as an array for the foreach function but it gives me this error: "Warning: foreach() argument must be of type array|object, null given in File path and line" and idk how to fix it and also how can i also link the echoed articles to other PhP files that are basically the article pages?

Edit: I managed to solve the problem by litteraly adding return $cursor; after the find and adding a $i variable for the immages so the article recordset rn is as it follows


function article_recordset(){
require 'vendor/autoload.php';

$client = new MongoDB\Client("mongodb://localhost:27017");
$i = 0;
$SiteArticles = $client->SiteArticles;
$articoli=$SiteArticles->Articles;
$cursor = $articoli->find();
return $cursor;

    foreach ($cursor as $articolo) {      
        $recordset = array(
            $i=$i+1 => array(
                "title" => $articolo["title"],
                "description" => $articolo["content"],
                "article" => "",
            )
        );
    }

} 

The lil change made the difference then for the immage system too later where i have an img folder with every img named with numbers from 0 to N

0

There are 0 answers