php如何获取mysql执行结果_如何在php mysql中获取结果的所有行?

bd96500e110b49cbb3cd949968f18be7.png

In my table I have 2 records with companyid = 1 , but when I run the php below for companyid = 1 it returns only the first one !

How can I fetch all the records?

The php file:

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

}

Using mysql_fetch_array is happening the same.

it returns {"product":[{"pid":"12371","productname":"test"}],"success":1}

when i run a query without parameters select * from table using mysql_fetch_array it returns all the rows ..

解决方案

As NikiC pointed out you should not be using the mysql_ functions any longer, you can fetch the entire array in both PDO and mysqli, Here is a example to fetch all rows using the mysqli->fetch_all function, hope this helps!

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值