如何在PHP MySQL中获取结果的所有行?

5
在我的表中,有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);
}

使用mysql_fetch_array也是一样的。当我运行一个没有参数的查询select * from table时,它会返回所有行:{"product":[{"pid":"12371","productname":"test"}],"success":1}


你需要循环遍历结果并读取每一行。将你的 if (mysql_num_rows...) 调用更改为 for 循环。 - Marvo
不要执行 $result = mysql_fetch_assoc($result);,因为这样会破坏 $result 数据。将其重命名为 $row 或其他名称。 - Hans Z
1
可能是重复的问题:基于查询将所有行获取到数组中 - nickb
4
请停止使用古老的 mysql_* 函数编写新代码。它们已不再得到维护,社区已开始 弃用过程。相反,您应该了解 prepared statements 并使用 PDOMySQLi。如果无法决定使用哪个,请参考 本文 进行选择。如果想学习,这是一个相当不错的 PDO 相关教程 - orourkek
此外,如果你使用PDO,只需调用fetchAll即可完成 :) - NikiC
@orourkek 我完全理解你的观点并且同意 - 在某种程度上。我们中的一些人必须维护过时的代码库中的旧代码,这需要学习过时的mysql_*函数以保持一致性。我不是这些函数的粉丝,更喜欢PDO或mysqli,但无法避免需要了解这些旧东西的情况。 - Ian Lewis
4个回答

35

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

3
fetch_all在我的Ubuntu上一开始无法工作 - 我需要执行以下操作:sudo apt-get install php5-mysqlnd,并重新启动apache。 - amurrell
$result = $this->sqlConn->query($sqlString);对我没有用,我不得不使用$result = $sqlConn->query($sqlString); - Kaspar Lee
1
@amurrell 我也得安装php5-mysqlnd,谢谢! - Fouad

8
while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}

mysql_free_result($result);

php.net/mysql_fetch_assoc

我建议您使用PDO而不是mysql_

if (!empty($result)) {

可能是 is_resource($result)


4
您需要循环遍历结果以获取所有行:
while($row = mysql_fetch_assoc($result)){
//Do stuff 
}

顺便提一下,您应该使用至少mysqli或PDO而不是mysql_*函数。


1
我已经编辑了上面的PHP代码...使用循环仍然得到相同的结果。 - mprog

1
我强烈认为使用Doctrine进行批处理或使用MySQL(PDO或mysqli)进行任何类型的迭代都只是一种幻觉。
@dimitri-k 提供了一个非常好的解释,特别是关于工作单元。问题在于误导:“ $query->iterate()”,它实际上并没有迭代数据源。它只是一个 \Traversable包装器,用于已经完全获取的数据源。
下面是一个示例,即使从完全删除Doctrine抽象层,我们仍会遇到内存问题
echo 'Starting with memory usage: ' . memory_get_usage(true) / 1024 / 1024 . " MB \n";

$pdo  = new \PDO("mysql:dbname=DBNAME;host=HOST", "USER", "PW");
$stmt = $pdo->prepare('SELECT * FROM my_big_table LIMIT 100000');
$stmt->execute();

while ($rawCampaign = $stmt->fetch()) {
    // echo $rawCampaign['id'] . "\n";
}

echo 'Ending with memory usage: ' . memory_get_usage(true) / 1024 / 1024 . " MB \n";

输出:

Starting with memory usage: 6 MB 
Ending with memory usage: 109.46875 MB

这里是关于令人失望的 getIterator() 方法:
namespace Doctrine\DBAL\Driver\Mysqli\MysqliStatement

/**
 * {@inheritdoc}
 */
public function getIterator()
{
    $data = $this->fetchAll();

    return new \ArrayIterator($data);
}

你可以使用我的小型库,实际上使用PHP Doctrine或DQL或纯SQL来流式传输大表格。无论你觉得合适的方式:https://github.com/EnchanterIO/remote-collection-stream

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接