Display SQL Results with Divi PHP Code Module

Written by Dan Mossop

The Divi PHP Code Module lets you easily add PHP code anywhere in your Divi Builder pages. One of the many things you can do with it is execute and display the results of SQL statements.

Here's an simple example. Suppose you want to display the titles of your 5 latest posts in a list. In that case, you can add the following code in to a Divi PHP Code Module:

 

global $wpdb;

// SQL query to fetch latest 5 posts
$query = "SELECT post_title, post_date FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 5";

// Execute the query
$results = $wpdb->get_results($query);

// Display the post titles, if any, as a list
if (!empty($results)) {
    echo '<ul>';
    foreach ($results as $post) {
        echo '<li>' . esc_html($post->post_title) . '</li>';
    }
    echo '</ul>';
} else {
    echo 'No posts found.';
}
Like so:
Then save the module and page, and when you view the site on the front-end you should see the results, like so:
Of course, this is just a basic example for demonstration, but there is no limit to what data you pull from the database, how you process it and how you display it.

We've used the $wpdb object here as it provides a clean way to interact with the database via SQL, but you can also use PHP's raw SQL functions should you need to.

Run PHP Code Directly in Your Divi Layouts

Unlock endless customization, automation, and dynamic functionality by seamlessly adding PHP code to your Divi pages and posts with the Divi PHP Code Module. Style, preview, and debug your PHP creations directly in the visual builder with robust error handling and enhanced security.

About Dan Mossop

Dan is a Scottish-born web developer, now living in Brisbane with his wife and son. He has been sharing tips and helping users with Divi since 2014. He created Divi Booster, the first Divi plugin, and continues to develop it along with 20+ other Divi plugins. Dan has a PhD in Computer Science, a background in web security and likes a lot of stuff, 

0 Comments

Submit a Comment

Comments are manually moderated and approved at the time they are answered. A preview is shown while pending but may disappear if your are cookies cleared - don't worry though, the comment is still in the queue.

Your email address will not be published. Required fields are marked *.

We may earn a commission when you visit links on our website.