WordPress is a great platform to build the any types of sites in now a days. It has a great functionality and feasibility to perform our own stuffs. Because of this feasibilty we can create our own code and plug that code into wordpress.
For the default wordpress tables they have already created functions like get_page(), wp_nav_menu(), etc. But for some custom plugin we need to fetch data from our own custom tables.
WordPress has given a great flexibility for this. WordPress uses the ezSQL PHP class to interation with the database. WordPress has provided the $wpdb class object which used to call the database related function.
Note: Make sure you globalize $wpdb to use in any custom function.
To run any query on Database using $wpdb:
Above function will return the integer based inserted/affected rows or selected rows. If any error occurs then it will return FALSE.
Please make sure that you escape the data entered by the user by the escape function before passing to the query like below.
Select Data using $wpdb:
WordPress has four functions to select the data from the database.
This function is used to fetch the single value from the database. Like total row count or sum of any column.
This function is used to fetch the entire row from the table. We can get the result in diffrent format base on second parameter of the function call. It can be Object, Associative Array or numerical indexed array.
This function used to fetch the single column from the table.
This function is used to get the results in normal way like to fetch multiple rows from one query. Returned data can be of various types like OBJECT, OBJECT_K, ARRAY_A and ARRAY_N.
Insert Rows using $wpdb:
Here is the basic usage for inserting rows in wordpress database using $wpdb.
name of the table to insert data into.
Key value paired array which holds the values to be inserted.
This is the optional and which can be %d for decimal, %s for string and $f for float.
Note: After successful insertion of the row the last inserted ID can be accessed via $wpdb->insert_id.
Update rows using $wpdb:
This function returns FALSE if error, or number of affected rows upon success.
name of the table to update the data into.
Key value paired array which holds the updated values for the row.
A named array which holds the column name as a key and value as a actual value for condition.
This is optional which defines the format for the $data array.
This is optional which defines the format for the $where array.