如何在php中获取JSON数据库表

时间:2014-07-22 13:23:45

标签: php mysql

我使用了这段代码

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

将表格的所有数据存储到2D数组中是否正确? 我如何在Ajax中使用这个数组作为json来显示HTML文件中的数据。

2 个答案:

答案 0 :(得分:1)

正如你在评论中提到的,你想做ajax和json。

您可以执行此类代码(使用mysql_fetch_assoc()代替数组):

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

和ajax(假设,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);
    }
});

安全注意:

  1. mysql_* functions are deprecated and will be removed from support, so you should avoid using it
  2. 使用mysqli_*PDO进行数据库查询。

答案 1 :(得分:0)

使用mysql_fetch_assoc而不是mysql_fetch_array ...

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

查看mysql_query文档以获取更多信息。但是,它建议您使用PDO或MySQLi驱动程序,因为从PHP 5.5.0开始不推荐使用它。