简体   繁体   中英

how to store data as an associative array from mysql database in php

I want to achieve to store data as an associative array from mysql database in php but when i just show the result in array form it show me the last inserted result in mysql table. My code:-

public function displayresult(){
    $result = mysql_query('SELECT * FROM user');
    $num = mysql_num_rows($result);
    if(mysql_num_rows($result) > 0){
        for($i=0;$i<=$num;$i++){        
            while($row=mysql_fetch_array($result)){
                $data[$i]['name']=$row['name'];
                $data[$i]['contact']=$row['contact'];
            }
        }
    }
    return $data;
}
print_r(displayresult());

and the result which above code showing is:-

 Array
  (
  [0] => Array
    (
        [name] => jason
        [contact] => 4098979774
    )

)

It doesn't showing me all results and just only the last inserted result. Please help.

You really don't need another complication with that, just push them normally:

public function displayresult(){
    $result = mysql_query('SELECT * FROM user');
    $num = mysql_num_rows($result);
    if(mysql_num_rows($result) > 0){  
        while($row = mysql_fetch_assoc($result)){ // use fetch_assoc 
            $data[] = array('name' => $row['name'], 'contact' => $row['contact']);
        }  
    }
    return $data;
}
print_r(displayresult());

Or better yet:

public function displayresult(){
    $result = mysql_query('SELECT name, contact FROM user');
    $num = mysql_num_rows($result);
    if(mysql_num_rows($result) > 0){  
        while($row = mysql_fetch_assoc($result)){
            $data[] = $row;
        }  
    }
    return $data;
}
print_r(displayresult());

Note: By the way, if possible, use the better extension which is mysqli or PDO instead.

Just remove the for loop from your code. When you have the foor loop in place, the inner while loop consumes the results and data related to all data gets inserted into the same index.

public function displayresult(){
    $result = mysql_query('SELECT * FROM user');
    $num = mysql_num_rows($result);
    if(mysql_num_rows($result) > 0){
        /* loop removed */       
        while($row=mysql_fetch_array($result)){
            $data[]=array("name"=>$row['name'],"contact"=>$row['contact']);
        }

    }
    return $data;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM