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:
Create a Database Connection: WordPress establishes a connection to the MySQL database automatically. You can use the global
$wpdbobject to interact with the database.
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;".
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;" );
- Check the Results: The result is returned as an array of objects. You can print the result like this:
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.