简体   繁体   English

如何在php中从mysql数据库将数据存储为关联数组

[英]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. 我想实现将数据作为关联数组从mysql数据库中的数据存储在php中,但是当我仅以数组形式显示结果时,它会向我显示mysql表中最后插入的结果。 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. 注意:顺便说一下,如果可能,请使用更好的扩展名,即mysqli或PDO。

Just remove the for loop from your code. 只需从代码中删除for循环即可。 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. 当您拥有foor循环时,内部的while循环将使用结果,并且与所有数据相关的数据都将插入到同一索引中。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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