CRUD operation using $wpdb
What is $wpdb?
- In WordPress,
$wpdbis a global object of the built-inwpdbclass. - It is automatically loaded and connected to your WordPress database (MySQL/MariaDB).
- It allows developers to interact with the database safely using methods for CRUD operations (Create, Read, Update, Delete).
The recommended way to access $wpdb in your WordPress PHP code is to declare $wpdb as a global variable using the global keyword, like this:
crate table in database
function akal_degree_college_student_table_direct() {
global $wpdb;(global object )
$table_name = $wpdb->prefix . “students”; // wp_students in database
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
firstname varchar(100) NOT NULL,
lastname varchar(100) NOT NULL,
class varchar(50) NOT NULL,
roll_number varchar(50) NOT NULL,
email varchar(100) NOT NULL,
phone varchar(20) NOT NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY roll_number (roll_number)
) $charset_collate;";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta($sql);
}
// run on theme activation (not every request)
add_action(‘after_switch_theme’, ‘akal_degree_college_student_table_direct’);