-1

It should be simple, but I just can't figure it out. I have a function, which returns an array, fetched from a MySql database. The returned array should have 2 elements.

Here is the function:

function path_to_photo ($id)
{
   $query = mysql_query("Select path from photos1 where listingsdb_id = $id"); 
   $test_array = mysql_fetch_array($query);

   return $test_array;
}

$one=2;
$test = path_to_photo($one); 
echo $test[0]; // --> this works fine
echo $test[1]; //-->this gives an error - undefined offset etc.

At first I thought my array returns actually only one element, but when I put

$query = mysql_query("Select path from photos1 where listingsdb_id=$id"); 
$test_array = mysql_fetch_array($query);

return sizeof($test_array);

it gives me correct number of 2. I just don't understand what happens with the second index. Here is the output of the query in MySQL

mysql> select path from photos1 where listingsdb_id=2;
+------------------+
| path             |
+------------------+
| small_photo.jpg  |
| big_photo.jpg |
+------------------+
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user2557930
  • 319
  • 2
  • 11
  • 1
    **Danger**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Jan 20 '15 at 11:35
  • 1
    `mysql_fetch_array` needs to be looped – Aditya Jan 20 '15 at 11:35

1 Answers1

2

mysql_fetch_array returns an array containing the data for the next row in the result.

You said Select path, so there is only one column in the result, so the array length should be 1.

If you want to get an array of all the paths then you will have to create an empty array, then call mysql_fetch_array repeatedly, putting each entry into the previously mentioned array in turn, and then return that array.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335