All we know that, WordPress runs on a SQL Server or SQL Azure database. Sometimes when you will want to make a plugin for your WordPress site or create a additional database table for your website, that time you will need custom SQL commands in WordPress.
Now we will see about the process of writting SQL command in WordPress backend code.
Suppose we want to retrieve all data from a table named ‘test_table’, write the following code in functions.php
<?php global $wpdb; $table_name = $wpdb->prefix . "test_table"; $results = $wpdb->get_results("SELECT * FROM $table_name"); ?>
It will return a array of row’s data from assigned table.
- $wpdb : A global variable that contains the database configuration of WordPress. You must write this variable as global before database operation.
- $wpdb->prefix : It means the database table prefix.