在我的表中我有2条记录companyid = 1,但是当我运行下面的php时,companyid = 1它只返回第一个!
我怎样才能获取所有记录?
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);
}
Run Code Online (Sandbox Code Playgroud)
使用mysql_fetch_array正在发生同样的事情.它返回{"product":[{"pid":"12371","productname":"test"}],"success":1}
当我运行没有参数的查询时select * from table使用mysql_fetch_array它返回所有行..
And*_*ham 32
正如NikiC指出你不应该再使用mysql_函数,你可以在PDO和mysqli中获取整个数组.这是一个使用mysqli-> fetch_all函数获取所有行的示例,希望这有帮助!
//Database Connection
$sqlConn = new mysqli($hostname, $username, $password, $database);
//Build SQL String
$sqlString = "SELECT * FROM my_table";
//Execute the query and put data into a result
$result = $sqlConn->query($sqlString);
//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
//Copy result into a numeric array
$resultArray = $result->fetch_all(MYSQLI_NUM);
//Copy result into both a associative and numeric array
$resultArray = $result->fetch_all(MYSQLI_BOTH);
Run Code Online (Sandbox Code Playgroud)
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
Run Code Online (Sandbox Code Playgroud)
我建议你使用PDO而不是mysql_
if (!empty($result)) {
Run Code Online (Sandbox Code Playgroud)
可能 is_resource($result)
您需要循环遍历结果以提取所有行:
while($row = mysql_fetch_assoc($result)){
//Do stuff
}
Run Code Online (Sandbox Code Playgroud)
附带说明一下,您应该至少使用 mysqli 或 PDO 而不是 mysql_* 函数。
| 归档时间: |
|
| 查看次数: |
68064 次 |
| 最近记录: |