hi i want to retrieve whole column from DB but store it in associative array. i write the code but its returning me only the last record. i want to return me the whole column. anyone can help?

public function GetMarks(){
        $query=mysql_query("SELECT name, marks FROM marks,users WHERE marks.id=users.id ");
        while($rows=mysql_fetch_assoc($query)){

            $name=$rows["name"];
            $mark=$rows["marks"];
            $fullmark=array("Name"=>$name,"Marks"=>$mark);
            $mk=json_encode($fullmark);
        }
        echo $mk;
}

I dont want to echo it in the while loop. because am sending the data to ajax and from there i am laerting the data. if i put it in the while loop i dont alert anything. outside while loop it alerts.how can i solve this problem?

Member Avatar for diafol
public function GetMarks(){
        $query=mysql_query("SELECT name, marks FROM marks,users WHERE marks.id=users.id ");
        while($rows=mysql_fetch_assoc($query)){
            $name=$rows["name"];
            $mark=$rows["marks"];
            $fullmark=array("Name"=>$name,"Marks"=>$mark);
            $mk=json_encode($fullmark);
        }
        echo $mk;
}

The reason you're getting just the last entry is that you're overwriting previous data. Try this:

partial class code
public function GetMarks(){
        $query=mysql_query("SELECT name, marks FROM marks,users WHERE marks.id=users.id ");
        $arr = array();
        while($rows=mysql_fetch_assoc($query)){
            $arr[] = array("Name"=>$rows["name"], "Marks=>$rows["marks"]);
        }
        if(!empty($arr)){
            $mk=json_encode($arr);
            return $mk;
        }
        return false;
}
client code
$obj = new Object; //or whatever it's called
if($mks = $obj->GetMarks()){
    //do ajax stuff with $mks
}

ok fine but now in ajax its returning me undefined! any idea why?

server.prototype.GetMarks=function(){
        $.ajax(
        {url:"getmarks.php",
        type:"POST",
        dataType:"json",
        success:function(data){
            alert(data.Name);


        }});
    }
Member Avatar for diafol

Well it would as data is an 'array' of sorts. Try

alert(data[0].Name);

You wanted an array of arrays. That will give you the first Name in the array. You can use js to loop over the items in 'data' to format the text to your needs.

thanks its working. but still am having another problem. how will i insert the data[i].name in another associative array? can you tell me?

Member Avatar for diafol

JS doesn't have associative arrays AFAIK. You have arrays and objects. But to all intents and purposes you can treat objects as such I suppose. This is turning out to be a 101 in js as opposed to php, so perhaps it would be better to ask the question in that forum?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.