AndreiBogdan
AndreiBogdan

Reputation: 11164

mysql_fetch_array receives 3 rows, but returns 4

I have the below PHP code:

$queryBlueprint = "SELECT * FROM `plan_photos` WHERE project_id=" . $projectId;
$resultBlueprints = mysql_query ( $queryBlueprint );
if ($resultBlueprints) {
    // Add the results into an array
    $blueprints [] = array ();
    echo mysql_num_rows ( $resultBlueprints ); /* --- this returns: 3 */
    while ( $row = mysql_fetch_array ( $resultBlueprints ) ) {
        $blueprints [] = $row;
    }
    echo "<br/>";
    echo count ( $blueprints ); /* --- this returns 4*/
    echo "<br/>";
    echo print_r ( $blueprints [0] );
    echo "<br/>";
    echo print_r ( $blueprints [1] );
    echo "<br/>";
    echo print_r ( $blueprints [2] );
    echo "<br/>";
    echo print_r ( $blueprints [3] );

Why does mysql_num_rows return 3, but after I add each result into an array, the array contains 4 items? The first ([0]) being "null" and the next 3 ([1], [2] and [3]) are what they're supposed to be (aka they contain data)

The echoed data:

3
4
Array ( ) 1 /*    <------ what is this?!?!    */ 
Array ( [id] => 8 [project_id] => 2 [photo] => http://webja5309b6cf8a525.jpg [title] => first ) 1
Array ( [id] => 9 [project_id] => 2 [photo] => http://webja7ee76.jpg [title] => second ) 1
Array ( [id] => 10 [project_id] => 2 [photo] => http://webj022d3.jpg [title] => third blueprint ) 1

The table if it helps:

CREATE TABLE IF NOT EXISTS `plan_photos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `project_id` int(11) NOT NULL,
  `photo` text NOT NULL,
  `title` varchar(50) NOT NULL,
  KEY `project_id` (`id`),
  KEY `project_id_2` (`project_id`)

Upvotes: 0

Views: 57

Answers (2)

Mike
Mike

Reputation: 24383

The reason is because you are adding an element in the declaration of the variable. Instead of doing:

$blueprints [] = array ();

Do

$blueprints = array();

Upvotes: 2

Your Common Sense
Your Common Sense

Reputation: 157870

$blueprints [] = array ();  // <------ this is that 

Upvotes: 1

Related Questions