Jump to content

Populate array from database -> Foreach loop


Solved_

Recommended Posts

I have a database table in wordpress, now I want to get all titles, content, order values out of the database and compile to a post and put them in an array. Nothing happens, no errors. If i change some code, I can get the first value, but not a repeated process, to fetch all data.

 

global $wpdb;

$sDB = $wpdb->get_results("SELECT my_title, my_content, my_order FROM my_table");
foreach ($sDB as $sDBOutput) {

  	$sATitle = $sDBOutput->my_title;	
$sAContent = $sDBOutput->my_content;
$sAOrder = $sDBOutput->my_order;

$sCompiled = '<div class="title">' . $sATitle . '</div><div class="content">' . $sAContent . '</div>';

$aPost = array();

$aPost[$sAOrder] = $sCompiled;
}

Link to comment
Share on other sites

Try this:

 

global $wpdb;

$aPost = array();
$sDB = $wpdb->get_results("SELECT my_title, my_content, my_order FROM my_table");
foreach ($sDB as $sDBOutput) {

  	$sATitle = $sDBOutput->my_title;	
$sAContent = $sDBOutput->my_content;
$sAOrder = $sDBOutput->my_order;

$sCompiled = '<div class="title">' . $sATitle . '</div><div class="content">' . $sAContent . '</div>';


if (isset($aPost[$sAOrder])) {
            // debug line
            echo 'overwriting existing key ' . $sAOrder . ' original: ' . $aPost[$sAOrder] . ' new: ' . $sCompiled . '<br>';
        }
$aPost[$sAOrder] = $sCompiled;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.