gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:10:00 26 4
gpt4 key购买 nike

在我的表中,我有 2 条 companyid = 1 的记录,但是当我为 companyid = 1 运行下面的 php 时,它只返回第一个!
如何获取所有记录?

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}当我运行不带参数的查询时 select * from table 使用 mysql_fetch_array 它返回所有行..

最佳答案

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

关于php - 如何在php mysql中获取结果的所有行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10940332/

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