What is $wpdb in WordPress and How to Use it for Database Security

$wpdb is a PHP global variable that holds the WordPress database object, which is actually an instantiation of the wpdb class.

$wpdb is used to manipulate custom database tables with security (prevent SQL injection attacks etc). If you want to manipulate common WordPress tables, use WP_Query instead.

Accessing the database directly should be avoided

The following code is valid, but you must always avoid it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
 * Insert customer.
 *
 * @param string $firstname - Customer first name.
 * @param string $lastname - Customer last name.
 *
 * @return int|string
 */
function insert_customer(
    string $firstname,
    string $lastname,
):int|string {
    $conn = new mysqli( 'db_server', 'db_user', 'db_passwd', 'db_name' );
 
    $sql = 'INSERT INTO customers (firstname, lastname) VALUES (?,?)';
 
    /* Prepare statement */
    $stmt = $conn->prepare( $sql );
 
    /* Bind parameters. Types: s = string, i = integer, d = double,  b = blob */
    $stmt->bind_param( 'ss', $firstname, $lastname );
 
    /* Execute statement */
    $stmt->execute();
 
    $insert_id = $stmt->insert_id;
 
    $stmt->close();
 
    return $insert_id;
}

Use $wpdb instead:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
 * Insert customer.
 *
 * @param string $firstname - Customer first name.
 * @param string $lastname - Customer last name.
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @return int|string
 */
function insert_customer(
    string $firstname,
    string $lastname,
):int|string {
    global $wpdb;
    $wpdb->show_errors(); // optional
    $bind_params = array(
        'firstname' => $firstname,
        'lastname'  => $lastname,
    );
    $params_type = array( '%s', '%s' ); // %s for string %d for digits etc
    $wpdb->insert( 'customers', $bind_params, $params_type );
 
    return $wpdb->insert_id;
}

References

Video