如何在php mysql中获取结果的所有行? [英] how to fetch all the row of the result in php mysql?

查看:268
本文介绍了如何在php mysql中获取结果的所有行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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的查询时,它将返回所有行..

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 ..

推荐答案

正如NikiC指出的那样,您不应该再使用mysql_函数了,您可以在PDO和mysqli中提取整个数组,这是一个示例使用 mysqli-> fetch_all 函数的所有行,希望这有帮助!

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

这篇关于如何在php mysql中获取结果的所有行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆