Solved_ Posted July 22, 2012 Share Posted July 22, 2012 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; } Quote Link to comment https://forums.phpfreaks.com/topic/266066-populate-array-from-database-foreach-loop/ Share on other sites More sharing options...
ignace Posted July 22, 2012 Share Posted July 22, 2012 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; } Quote Link to comment https://forums.phpfreaks.com/topic/266066-populate-array-from-database-foreach-loop/#findComment-1363411 Share on other sites More sharing options...
Solved_ Posted July 22, 2012 Author Share Posted July 22, 2012 Thanks that worked, am i right, that the only change is $aPost = array(); to above (except the debug ofcourse)? I was empting the array every time.. Quote Link to comment https://forums.phpfreaks.com/topic/266066-populate-array-from-database-foreach-loop/#findComment-1363414 Share on other sites More sharing options...
ignace Posted July 22, 2012 Share Posted July 22, 2012 Correct. Quote Link to comment https://forums.phpfreaks.com/topic/266066-populate-array-from-database-foreach-loop/#findComment-1363448 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.