2

I'm trying to create a multidimensional array within a PHP function. But it doesn't seem to work. The function I wrote:

//Get newsitems
function getNews() {
    $result = mysql_query("SELECT * FROM news WHERE archived='0' ORDER BY `id` DESC")
    or die(mysql_error());

    $array = array();

    while($row = mysql_fetch_array($result)) {

        $array[] =  array ( 'title' => $row['title'], 
                            'content' => $row['content'], 
                            'date' => $row['pagid'], 
                            'image' => $row['image'], 
                            'youtube' => $row['youtube']

    }

    return $array;
}

Then I'm trying to get an array by doing this:

$aNews = getNews();

When I print this array nothing is showed. What am I doing wrong? The database query doesn't return any errors.

1 Answer 1

2

You have a syntax error, you didn't close the parenthesis and terminate the line around the array.

Change to:

    $array[] =  array ( 'title' => $row['title'], 
                        'content' => $row['content'], 
                        'date' => $row['pagid'], 
                        'image' => $row['image'], 
                        'youtube' => $row['youtube'] ); // <-- this

You should be getting a fatal error because of this, a white screen usually indicates a fatal error but with error reporting/display turned off. For future debugging you can view your error log or turn errors on:

error_reporting(E_ALL);
ini_set('display_errors', '1');

Side notes:

  • The mysql_* library is deprecated, consider upgrading to a modern API such as MySQLi or PDO.
  • If you must use this library, at least change to mysql_fetch_assoc() because you're only interested in the associative array.
Sign up to request clarification or add additional context in comments.

9 Comments

Thanks. I had a syntax error indeed. But the problem I had regarding getting nothing back from the function still exists..
Then it looks like no rows were returned from the query. See what this outputs after the query: var_dump(mysql_num_rows($result));
var_dump returns nothing. That's weird because this query should return something..
What do you mean nothing? it should either output a number (could be 0) or false on failure.
I have added the var_dump in my function in $error and then return $error; Then when I echo getNews(); I get nothing. I hope I am explaining this clearly.
|

Your Answer

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