Custom SQL Query for WordPress page

I’m quite new to wordpress.
I’m trying to build a tableview within a wordpress page. Therfore I need a custom SQL Query to my MySQL Database.

  1. Query data from my MySQL Database
  2. Get the result somehow in a HTML format in order to display it in a table view within a wordpress page.

My question is:
How can I use the wpdb_class in a wordpress page when it is not an option to put php code in a page?

Related posts

2 comments

  1. The wpdb object can be used to run arbitrary queries against the WordPress database. Let’s say you want to list the most recent 4 posts:

    $results = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE `post_type`='post' LIMIT 4" );
    

    The $wpdb->posts variable will output the table name for posts. It’s usually wp_posts, but if you’re using a custom database prefix this could be different.

    However, if you’re trying to grab post data (or custom post data or meta information or user data or … anything built-in to WordPress), you should really be using WP_Query.

    Here’s the same query above, re-written for WP_Query:

    $query = new WP_Query(
        array(
            'post_type'      => 'post',
            'posts_per_page' => 4
        )
    );
    

    The advantage of using WP_Query is that it will automatically join against the post meta table and return an array of WP_Post objects that you can work with and loop through.

  2. <?php 
    global $wpdb;
    $post_id = $wpdb->get_results("SELECT post_id FROM $wpdb->postmeta WHERE (meta_key = 'mfn-post-link1' AND meta_value = '". $from ."')");
        print_r($post_id); /
    ?>
    

    Define global variable $wpdb then make custom query and pass $wpdb->get_results();

Comments are closed.