Sometimes we need to access a database on another server in Worpdress, you can use the following way, add the following code in functions.php:
// 输入数据库配置参数
$mydb = new wpdb('username','password','database','localhost'); $rows = $mydb->get_results("select Name from my_table"); echo "<ul>"; foreach ($rows as $obj) : echo "<li>".$obj->Name."</li>"; endforeach; echo "</ul>";
After creating a connection you can use wordpress comes with a number of database functions
$sum = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) from table_name where post_status = 'publish' and user_id = %d", $user_id ) ); printf('This user has %d posts', $sum);
wordpress built-in database operations like check out the following official link:
https://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks