Fetching data from MySQL via PHP in WordPress sometime required to execute PHP within post or page instead of using a plugin. Please note that, MySQL is everything for WordPress like Content Management System and if you do not know what you are doing, you can easily get hacked. We belong to just MySQL user after Installing MySQL, Handling MySQL from command line, using WordPress and other CMS for many long years.
So, kindly use these kind of trial and error experiments on localhost or dev installation for either directly testing any snippet in this guide on fetching data from MySQL via PHP in WordPress or by some modification.
Fetching Data from MySQL via PHP in WordPress : Reference for Function
Even if you are great to handle MySQL, you must read the Class Reference for wpdb in WordPress documentation :
Additionally, some themes, Plugins can change the default behavior of WordPress. The query function allows you to execute any SQL query on the WordPress database. It is best to use a more specific function for SELECT queries.
One must be very very careful while fetching data from MySQL, echoing them and using a HTML form simultaneously. SQL Injection is not uncommon with buggy plugins or limited usage Plugins (for private usage). For serious works, please consult a good developer.
It is better to user alternative WordPress function, whenever possible. All data in SQL queries must be SQL-escaped before the SQL query is executed to prevent against SQL injection attacks.
Fetching Data from MySQL via PHP in WordPress : Example
Do keep in mind that for posts/pages from the
wp_posts table you would use
Normally we can use this to restore post data :
Or can perform a more complex work :
For example, this is a typical example to fetch data and echo it :
Post Author 1 is usually the Admin (we wrote once not to use the installation account for Publishing for hardening WordPress).
These methods can be executed very beautifully to generate dynamic custom result.
Follow the Author of this article :