Reputation: 135
I have a function.php file in my plugin I am making and I want a function that gets all data from a table in the DB then stores it in a $data array. My problem is when I call the function outside the functions file the array is null, if I dump the data array out inside the function and then call the function the data is present so I know the query is successful. Here is my code:
functions.php
function getCategories() {
$data = array();
global $wpdb;
$data = $wpdb->get_results("SELECT * FROM `metal_work_categories` WHERE 1", ARRAY_N);
}
index.php
include('functions.php');
getCategories();
var_dump($data);
I also tried initializing the data array in the index.php file and passing it to the function, just a wild stab in the dark really, to no avail:
$data = array();
getCategories($data);
var_dump($data);
Upvotes: 0
Views: 30
Reputation: 7005
That's how variable scope works. You need to return the data you want from the function, and assign it to a variable.
function getCategories() {
global $wpdb;
return $wpdb->get_results("SELECT * FROM `metal_work_categories` WHERE 1", ARRAY_N);
}
$data = getCategories();
PS: Next up, stop using global!
Upvotes: 2