DJDMorrison
DJDMorrison

Reputation: 1327

SQL results to PHP array

I've got the following sql query:

$sql = "SELECT lat, lang
        FROM users";

I then use the following code to put the results of the array into two arrays, one for lat and one for lang.

$i = 0;

foreach($results as $row) {
    $latArray = array();
    $langArray = array();
    $latArray[$i] = $row['lat'];
    $langArray[$i] = $row['lang'];          
    $i = ($i + 1);
}

However, it seems that only the last value that is passed to the array is stored. When I echo out each value of the array I get the following error: Undefined offset: 0 which I believe means theres nothing at latArray[0].

I'm sure I've missed something obvious here but why aren't all the values copied to the new array?

Upvotes: 0

Views: 90

Answers (4)

use fetch_assoc instead:

$latArray = array();
        $langArray = array();
    while($row = mysql_fetch_assoc($your_query)){



    $latArray[$i] = $row['lat'];
    $langArray[$i] = $row['lang'];          
    $i++;
}

if u are using msqli us mysqli_fetch_assoc

Upvotes: 0

user1317647
user1317647

Reputation:

You should put

$latArray = array();
$langArray = array();

Before foreach cycle (like you do with your counter $i), 'cause with every new value from $result it resets thous values..

so your code will look like:

$i = 0;
$latArray = array();
$langArray = array();
foreach($results as $row) {
    $latArray[$i] = $row['lat'];
    $langArray[$i] = $row['lang'];          
    $i = ($i + 1);
}

Upvotes: 1

TheEwook
TheEwook

Reputation: 11117

Declare your array before the loop

$latArray = array();
$langArray = array();

foreach($results as $row) {
    $latArray[$i] = $row['lat'];
    $langArray[$i] = $row['lang'];          
    $i = ($i + 1);
}

Upvotes: 1

sybear
sybear

Reputation: 7784

$i = 0;
$latArray = array(); //Declare once, do not redeclare in the loop
$langArray = array();
foreach($results as $row) {
    $latArray[$i] = $row['lat'];
    $langArray[$i] = $row['lang'];          
    $i = ($i + 1);
}

Upvotes: 3

Related Questions