How to Run a MySQL Query in WordPress?

Running a MySQL query in WordPress is a powerful way to interact directly with your website’s database. However, this should be done with care as incorrect queries can disrupt your site.

Here’s how you can run a MySQL query in WordPress:

  1. Create a Database Connection: WordPress establishes a connection to the MySQL database automatically. You can use the global $wpdb object to interact with the database.

  2. Create Your Query: Construct your query in SQL. For example, to get the title of a specific post, your SQL query would look something like this: "SELECT post_title FROM wp_posts WHERE ID = 1;".

  3. Run the Query: Use the $wpdb->get_results() function to run your query. If you were using the above example, it would look like this:

global $wpdb;
$result = $wpdb->get_results( "SELECT post_title FROM wp_posts WHERE ID = 1;" );
  1. Check the Results: The result is returned as an array of objects. You can print the result like this: echo $result[0]->post_title;.

Remember, always back up your website and its database before running any MySQL queries to protect against data loss from errors.

Also, it’s important to sanitize any user input included in your queries to protect against SQL injection attacks.

Leave a Comment