gpt4 book ai didi

php - 使用ajax php mysql从各种查询中检索多个数据

转载 作者:行者123 更新时间:2023-11-29 00:07:42 25 4
gpt4 key购买 nike

我是 Ajax 和 JSON 表示法的新手,所以我试图从数据库的不同表中获取数据,如国家名称、州名称、部门名称、工作职位等数据,我已经看到了示例通过 JSON 可以获取数据,但只能从一个表中获取数据,你能给我一点帮助吗?我怎样才能用多个表来完成它并将它保存在一个数组中。

<?php 


$host = "localhost";
$user = "usuer";
$pass = "password";

$databaseName = "jsonExample";
$tableName = "variables";


$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);


$result = mysql_query("SELECT * FROM $tableName"); //query
//$array = mysql_fetch_row($result); //fetch result
if(mysql_num_rows($result) <= 0){

}else{
while($obj = mysql_fetch_row($result)){
$array[] = $obj;
}
}

echo json_encode($array);

?>

HTML 文件:

<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>-->


<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text will be replaced</div>

<script id="source" language="javascript" type="text/javascript">

$(function ()
{


$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{

var id = data[0]; //get id
var vname = data[1]; //get name



$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
//recommend reading up on jquery selectors they are awesome http://api.jquery.com/category/selectors/
}
});

});
</script>

</body>
</html>

最佳答案

如果您希望将多个查询的结果放在一个数组中,您可以将每个结果添加到一个键中。 F.i.如果你查询表 table1 到 tablen ...

// define the array that will contain all result sets
$array = [];

// create an array for the result set coming from table 1
$array['table1']= [];
$result = mysql_query("SELECT * FROM table1");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table1'][] = $obj;
}
}

// create an array for the result set coming from table 2
$array['table2']= [];
$result = mysql_query("SELECT * FROM table2");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table2'][] = $obj;
}
}
::
::
// create an array for the result set coming from table n
$array['tablen']= [];
$result = mysql_query("SELECT * FROM tablen");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['tablen'][] = $obj;
}
}

// return the results formatted as json
return json_encode($array);

在 javascript 中,您可以使用 data->table1 访问 table1 的结果。

提示

使用 mysqli 而不是 mysql。它是mysql的改进版本。检查 this question 的答案一些背景。

关于php - 使用ajax php mysql从各种查询中检索多个数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26740658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com