1

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.

2 Answers 2

4

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.

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.