Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

how to fetch all the row of the result in php mysql?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...