16

Some code here, I want store mysql query result into an array with php, but my code return result: 2h, not what I wish.(the correct result should be 36,35,34,33,32)

<?php
set_time_limit(59);
mysql_select_db("mycoon",$db);
mysql_query("SET NAMES utf8"); 
$result = mysql_query("SELECT id,link FROM mytable Order By id DESC LIMIT 0,5");
$new_array[] = $row;
while ($row = mysql_fetch_array($result)) {
    $new_array[$row['id']] = $row;
    $new_array[$row['link']] = $row;
}
mysql_close($db);// close mysql then do other job with set_time_limit(59)
foreach($new_array as $array){
    echo $array['id'].'<br />';
    echo $array['link'].'<br />';
}
?>

Result:

36
http://localhost/img/img36.jpg
36
http://localhost/img/img36.jpg
35
http://localhost/img/img35.jpg
35
http://localhost/img/img35.jpg
34
http://localhost/img/img34.jpg
34
http://localhost/img/img34.jpg
33
http://localhost/img/img33.jpg
33
http://localhost/img/img33.jpg
32
http://localhost/img/img32.jpg
32
http://localhost/img/img32.jpg
3

3 Answers 3

53

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

Sign up to request clarification or add additional context in comments.

1 Comment

@fishman I've update it. Did you use it like this, or did you put $new_array[] twice there?
4

Use mysql_fetch_assoc instead of mysql_fetch_array

http://php.net/manual/en/function.mysql-fetch-assoc.php

2 Comments

It's kinda funny to see that the function that makes an array is called assoc instead array :-)
mysql_fetch_assoc is deprecated since PHP 7.0: php.net/manual/en/function.mysql-fetch-assoc.php Use mysqli_fetch_assoc instead
4

What about this:

while ($row = mysql_fetch_array($result)) 
{
    $new_array[$row['id']]['id'] = $row['id'];
    $new_array[$row['id']]['link'] = $row['link'];
}

To retrieve link and id:

foreach($new_array as $array)
{       
   echo $array['id'].'<br />';
   echo $array['link'].'<br />';
}

2 Comments

You're not initializing $new_array[ $row['id']] as array. Wouldn't $new_array[ $row['id']] = array( 'id' => $row['id'], 'link' => $row['link']); (assuming that you WANT and need change values/keys) work faster?
$row['id'] is dynamic so in a loop, $new_array[$row['id']] looks like: $new_array[1] = '...', $new_array[2] = '...',$new_array[3] = '...' ,etc, try print_r($new_array);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.