WordPress talk to database with an instantiated of WPDB class that $wpdb do it as a global object. indeed an object of wpdb class can talk to any tables of only one database at a time.
$wpdb is a global object provided by WordPress for interacting with the database. It is an instance of the wpdb class, which is responsible for managing database connections and executing SQL queries.
Certainly! $wpdb is a global object provided by WordPress for interacting with the database. It is an instance of the wpdb class, which is responsible for managing database connections and executing SQL queries. Here are some of the things that $wpdb can do:
- Connect to the database: $wpdb uses the credentials specified in the wp-config.php file to connect to the database. Once connected, it can execute queries and retrieve results.
- Execute SQL queries: $wpdb has methods for executing different types of SQL queries, such as query, get_results, get_var, and get_row. These methods take an SQL query as an argument and return the results of the query.
- Sanitize input: $wpdb provides methods for sanitizing input before including it in an SQL query, such as prepare and esc_like. These methods help to prevent SQL injection attacks.
- Manage transactions: $wpdb has methods for starting, committing, and rolling back transactions. Transactions can be used to ensure that multiple SQL queries are executed atomically, so that either all of them succeed or none of them do.
- Cache query results: $wpdb can cache query results for a specified amount of time, to improve performance and reduce the load on the database server.
Overall, $wpdb is a powerful and flexible tool for working with databases in WordPress. It is widely used throughout the WordPress codebase and by WordPress plugins and themes.
In following, we describe how to use $wpdb in developing WordPress theme or plugin with respect of OOP (object oriented programming)
One of the simplest way is to define all methods of wpdb class in a specific class of our plugin or theme. Here we named this class MyDB
class MyDB { private $wpdb; function __construct() { global $wpdb; $this->wpdb = $wpdb; } function query($sql) { return $this->wpdb->query($sql); } function get_results($sql) { return $this->wpdb->get_results($sql); } function get_var($sql) { return $this->wpdb->get_var($sql); } function get_row($sql) { return $this->wpdb->get_row($sql); } }
This class has a constructor that initializes the $wpdb object, which is a global object provided by WordPress for database connectivity. The query, get_results, get_var, and get_row functions all call the corresponding methods of the $wpdb object to execute SQL queries and retrieve results. To use this class, you can create a new instance of MyDB and then call its methods to interact with the database. For example
$mydb = new MyDB(); $results = $mydb->get_results("SELECT * FROM my_table");