gpt4 book ai didi

php - 使用 mysql_fetch_array() 函数捕获多行结果

转载 作者:行者123 更新时间:2023-11-29 08:23:24 26 4
gpt4 key购买 nike

我有一个 php 函数,可以从 mySQL 数据库捕获某个地点的坐标并返回结果:

public function getCoordinatesByName($name) {
$result = mysql_query("SELECT * FROM places WHERE name = '$name'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
return $result;
} else {
// user not found
return false;
}
}

该函数在index.php中用于捕获结果并通过JSON将其发送到Android设备:

$place = $db->getCoordinatesByName($name);
if ($place != false) {
// user found
// echo json with success = 1

$response["success"] = 1;
$response["place"]["H"] = $place["H"];
$response["place"]["V"] = $place["V"];
$response["place"]["placeid"] = $place["placeid"];
$response["place"]["name"] = $place["name"];
$response["place"]["type"] = $place["type"];
$response["place"]["note"] = $place["note"];
$response["place"]["discription"] = $place["discription"];
//$response["place"]["created_at"] = $user["created_at"];
//$response["place"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
}

现在我想立即发送所有地点的所有坐标,我创建了一个名为 getCooperatives 的函数:

 public function getCoordinates($name) {
$result = mysql_query("SELECT * FROM places") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
return $result;
} else {
// user not found
return false;
}
}

然后我在index.php中这样使用它:

 $place = $db->getCoordinates($name);
if ($place != false) {
for ($i = 1;$i = count($place); $i++ ) {
// user found
// echo json with success = 1
$response[$i]["success"] = 1;
$response[$i]["place"]["H"] = $place[$i]["H"];
$response[$i]["place"]["V"] = $place[$i]["V"];
$response[$i]["place"]["placeid"] = $place[$i]["placeid"];
$response[$i]["place"]["name"] = $place[$i]["name"];
$response[$i]["place"]["type"] = $place[$i]["type"];
$response[$i]["place"]["note"] = $place[$i]["note"];
//$response["place"]["created_at"] = $user["created_at"];
//$response["place"]["updated_at"] = $user["updated_at"];
}
echo json_encode($response);
}

我认为有些不对劲,因为当我从 Android 设备运行应用程序时总是出现错误

最佳答案

mysql_fetch_array()(及其近亲_assoc_object)返回单个ROW数据。它们不会获取整个查询结果。您需要构建一个行数组,然后返回该数组:

$data = array();
while($row = mysql_fetch_array($result)) {
$data[] = $row;
}
return $data;

然后您将获得可以迭代的数组。

关于php - 使用 mysql_fetch_array() 函数捕获多行结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18662428/

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