Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting MySql table data into an array

I try to catch data from mysql to put them all in array. Suppose:

    users table
    -----------------------
    id| name | code 
    ----------------------
    1| gorge | 2132
    2| flix | ksd02
    3| jasmen | skaod2

    $sql = mysql_query("select id, name, code from users");
    $userinfo = array()
    while($row_user = mysql_fetch_array($sql)){
    $userinfo = $row_user[name] 
    }
-------------------------
foreach($userinfo as $usinfo){
echo $usinfo."<br/>";
}

Here is the problem i can only insert user name but cant insert also code & id in userinfo array please help me to insert all data in same array.

[P.S] No object oriented please.

like image 735
Kareem Nour Emam Avatar asked Jan 18 '11 21:01

Kareem Nour Emam


3 Answers

$sql = mysql_query("select id, name, code from users");
$userinfo = array();

while ($row_user = mysql_fetch_assoc($sql))
    $userinfo[] = $row_user;

This will give you $userinfo as an array with the following structure:

[
    [id => 1, name => 'gorge', code => '2123'],
    [id => 2, name => 'flix', code => 'ksd02'],
    [id => 3, name => 'jasmen', code => 'skaod2']
]

If you want to output the data:

foreach ($userinfo as $user) {
    echo "Id: {$user[id]}<br />"
       . "Name: {$user[name]}<br />"
       . "Code: {$user[code]}<br /><br />";
}
like image 127
5 revs, 2 users 97% Avatar answered Nov 17 '22 10:11

5 revs, 2 users 97%


while($row_user = mysql_fetch_assoc($sql)){
   $userinfo[] = $row_user;
}

foreach($userinfo as $usrinfo){
   echo "Id: ".$usrinfo['id']."<br />";
   echo "Name: ".$usrinfo['name']."<br />";
   echo "Code: ".$usrinfo['code']."<br />";
}
like image 5
Phill Pafford Avatar answered Nov 17 '22 10:11

Phill Pafford


I found this code and I save my day:

<?php
$sql=mysql_query("select * from table1");

/*every time it fetches the row, adds it to array...*/
while($r[]=mysql_fetch_array($sql));

echo "<pre>";
// Prints $r as array 
print_r ($r);
echo "</pre>";
?>
like image 4
Christos Papoulas Avatar answered Nov 17 '22 10:11

Christos Papoulas