1

How can I take my table I created like this:

global $wpdb; //Get all the wordpress database stuff
$table_prefix = $wpdb->base_prefix; //Get the global prefix for all sites (on a multisite installation)
$table_name = $table_prefix.'wpaa';//Add   wpaa   behind the prefix 

$sql = "CREATE TABLE IF NOT EXISTS `".$table_name."` (....) "; //Create table and its rows. (Rows are ...'d out)

require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); //Require something you have to include
dbDelta( $sql ); //Make the actual query

and get all the data out from it in form of an array.


I know how I would do in regular PHP (without wordpress):

$sql = 'SELECT id,foo,bar FROM wp_wpaa';
$result = mysql_query($sql) or die('Error at looking up in database');
$array = mysql_fetch_array($result);
1
  • You are familiar with $wpdb. Check the Codex. Everything you need for this is there.
    – s_ha_dum
    Mar 9, 2013 at 22:26

2 Answers 2

3

$wpdb->get_results(); has a second parameter for the return format:

/**
 * Retrieve an entire SQL result set from the database (i.e., many rows)
 *
 * Executes a SQL query and returns the entire SQL result.
 *
 * @since 0.71
 *
 * @param string $query SQL query.
 * @param string $output Optional. 
 * Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants. 
 * With one of the first three, return an array of rows indexed from 0 by SQL 
 * result row number.
 *  Each row is an associative array (column => value, ...), a numerically 
 *      indexed array (0 => value, ...), or an object. ( ->column = value ), 
 *      respectively.
 *  With OBJECT_K, return an associative array of row objects keyed by the 
 *      value of each row's first column's value. Duplicate keys are discarded.
 * @return mixed Database query results
 */
function get_results( $query = null, $output = OBJECT ) {

So this will return an array:

$result = $wpdb->get_results( $sql, ARRAY_A );
1
  • Tank you! I just didn't know how to get the output as an array
    – LukasFT
    Mar 10, 2013 at 9:44
0

you can take every rows from a table YOUR_TABALE_NAME

"SELECT * FROM {$wpdb->prefix}YOUR_TABALE_NAME"

then with the get_results() return it into an array $array

finally you have somthing like this one :


    global $wpdb;
    $array = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}YOUR_TABALE_NAME");
    print_r($array); // print the array

1
  • The original question wanted each row to be an array though, and the extra parameter in the other answer does that I think. How is this different to / better than the other answer?
    – Rup
    Jun 6, 2022 at 17:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.