0

i used this code

$dbhandle = mysql_connect("localhost","root","password")
or die("Unable to connect to MySQL");

$arr;

//select a database to work with
$selected = mysql_select_db("info",$dbhandle)
or die("Could not select examples");

$result = mysql_query("SELECT * FROM students");

while($row = mysql_fetch_array($result))
{
    $arr[]=$row;
}

Is it right way to store all data of a table into a 2D array. And how i use this array in Ajax as json to show data in a HTML file.?

ztripez
  • 664
  • 6
  • 24
Aniket Singh
  • 2,464
  • 1
  • 21
  • 32

2 Answers2

1

As you mentioned in comments, that you want to do ajax and json.

You can do code like this (use mysql_fetch_assoc() instead of array):

//set content type: text/json
header("Content-Type: text/json");

$dbhandle = mysql_connect("localhost","root","password") or die("Unable to connect to MySQL");

//select a database to work with
$selected = mysql_select_db("info",$dbhandle) or die("Could not select examples");

$result = mysql_query("SELECT * FROM students");

if(mysql_num_rows($result)>0){
    $rows=array();
    while($row = mysql_fetch_assoc($result))
    {
        $rows[]=$row;
    }
    echo json_encode(array("success"=>$rows));
}else{
    echo json_encode(array("error"=>"No records found."));
}
exit;

and for ajax (assuming, jQuery.get() AJAX)

$.get("script.php", function(data){
    if(data.success){
        //process each row
        data.success.forEach(function(row){
            console.log(row); //access student row here, simply like row.student_name, row.city etc.
        });
    }else{
        alert(data.error);
    }
});

Scurity Note:

  1. mysql_* functions are deprecated and will be removed from support, so you should avoid using it.
  2. use mysqli_* or PDO for database queries.
Community
  • 1
  • 1
Ravi Dhoriya ツ
  • 4,435
  • 8
  • 37
  • 48
0

Use mysql_fetch_assoc instead of mysql_fetch_array...

while ($row = mysql_fetch_assoc($result)) {
    $arr[]=$row; 
}

Check mysql_query documentation for more information. However, its recommended that you use PDO or MySQLi drivers as this is deprecated as of PHP 5.5.0.

Akshay Raje
  • 852
  • 9
  • 20