在我的表中我有2条记录companyid = 1
,但是当我运行下面的companyid = 1
时,它只返回第一个!
如何获取所有记录?如何在php mysql中获取结果的所有行?
PHP文件:
if (isset($_GET["companyid"])) {
$companyid = $_GET['companyid'];
// get a product from products table
$result = mysql_query("SELECT * FROM `products`
WHERE companyid = $companyid;");
if (!empty($result)) {
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)){
$product = array();
$product["pid"] = $row["pid"];
$product["productname"] = $row["productname"];
}
$response["product"] = array();
array_push($response["product"], $product);
// success
$response["success"] = 1;
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no product JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
使用mysql_fetch_array
正在发生的事情一样。 返回{"product":[{"pid":"12371","productname":"test"}],"success":1}
当我运行,而无需使用mysql_fetch_array
返回所有行参数select * from table
查询..
你需要遍历结果并读入每一行。将您的if(mysql_num_rows ...)调用更改为for循环。 – Marvo
不要执行'$ result = mysql_fetch_assoc($ result);'当你这样做时,你正在销毁你的'$ result'数据。重命名它'$行'或东西 –
可能重复[基于查询获取所有行到数组中](http://stackoverflow.com/questions/9931684/fetch-all-rows-based-on-the-query -into-an-array) – nickb