2

I am trying to store data in an array, and then output a key of that array whenever I want. I have a table of staff data and am successfully using print_r to print the array, but cannot use "echo $staff_data;" to do anything. I feel like I am very close, but it is slipping by me.

I have two functions:

function staff_data() {
    $staff_data = array();
    $query = mysql_query("SELECT * FROM `staff`");
    while ($row = mysql_fetch_assoc($query)) {
    $staff_data[] = $row;
    }
}

function output_staff($staff_data) {
return '<ul><li>' . implode('</li><li>', $staff_data) . '</li></ul>';
}

I am not receiving the correct output. Currently I get these errors:

Notice: Undefined variable: staff_data in C:\xampp\htdocs\projects\etk\internal\staff.php >on line 11

Warning: implode(): Invalid arguments passed in C:\xampp\htdocs...line 3

which is pointing to my output_staff function. Can someone point me in the right direction?

4
  • Where are you calling output_staff()? It looks like you aren't passing an array to that function. Commented Nov 15, 2013 at 22:38
  • When you call output_staff(), are you passing in a variable like so? output_staff($myArray); Commented Nov 15, 2013 at 22:39
  • i think in the first functions is missing a return, return $staff_data; Commented Nov 15, 2013 at 22:39
  • Yes, am writing this in my actual page: echo output_staff($staff_data); Commented Nov 16, 2013 at 14:39

1 Answer 1

2

And how are your functions related? Your staff_data() seems to be returning nothing (i.e. null). And your output_staff() returns string, so you need to output it. So that should be:

function staff_data() 
{
    $staff_data = array();
    $query = mysql_query("SELECT * FROM `staff`");
    while ($row = mysql_fetch_assoc($query)) {
       $staff_data[] = $row;
    }
    return $staff_data;
}
//code 

$data = staff_data();
echo output_staff($data);
Sign up to request clarification or add additional context in comments.

2 Comments

Fair play, I wasn't returning anything. I added the return and used a variable to store the array returned from staff_data() but I get this array to string conversion error, which I have seen before. I thought that was what my implode was taking care of. I guess at this point I don't understand the error message completely
I would like to add that using print_r on your $data variable totally works, as we would expect. I am looking up this string to conversion error, and I am thinking that the problem lies in my output_staff() function that is trying to output a string, when really its handling an array

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.