The $wpdb class is WordPress’s database access abstraction layer. It provides methods for querying the database, inserting and updating data, and handling table prefixes. Using $wpdb instead of raw PHP database functions ensures compatibility across different database configurations and provides built-in security features.
Getting Started
Access $wpdb globally with global $wpdb. The object automatically connects to the WordPress database with the credentials from wp-config.php. Use $wpdb->prefix to access the table prefix. Common properties include $wpdb->posts, $wpdb->postmeta, $wpdb->users, and $wpdb->options for direct table access.
Select Queries
Use $wpdb->get_results() for queries returning multiple rows, $wpdb->get_row() for a single row, $wpdb->get_var() for a single value, and $wpdb->get_col() for a single column. Always use $wpdb->prepare() with placeholder syntax for dynamic values – %s for strings, %d for integers, %f for floats.
Insert and Update
Use $wpdb->insert() for inserting data with automatic sanitization. Pass the table name and an associative array of column-value pairs. Use $wpdb->update() for updating existing rows with a WHERE clause. Both methods return the number of rows affected or false on error.
Prepared Statements
Never concatenate values directly into SQL queries. Use $wpdb->prepare() with %s, %d, and %f placeholders. For IN() clauses with arrays, generate placeholders with array_fill and implode. Prepared statements prevent SQL injection attacks automatically.
Error Handling
Check for errors after database operations. Use $wpdb->last_error to get the last error message. Use $wpdb->last_query to debug the last executed query. Use WP_DEBUG to display database errors during development. Log errors for production debugging.
Il punto fondamentale
The wpdb class provides a secure, WordPress-idiomatic way to interact with the database. Use prepared statements for all queries, leverage helper methods for inserts and updates, handle errors gracefully, and respect the table prefix. Proper wpdb usage ensures your plugin’s database operations are secure and compatible.




