PHP - 执行选择查询并循环结果

时间:2015-09-01 17:33:45

标签: php mysql select

我正在使用PHP开发Web服务。我在执行select查询时遇到了一些麻烦。这是我正在使用的代码。

DB_Functions.php

public function getCompanies() {

    $result = mysql_query("SELECT * FROM company");
    // check for successful store

    if ($result) {
        return mysql_fetch_array($result,true);
    } else {
        return false;
    }
}

GetCompanies.php

<?php

require_once 'include/DB_Functions.php';
$db = new DB_Functions();

$companies = array();
//$rows = $db->getCompanies();

while ($row = $db->getCompanies()) {
    echo $row['companyName'];
    $rowArr = array();
    $rowArr['CompanyName'] = $row['companyName'];
    $rowArr['CompanyID'] = $row['companyId'];
    //array_push($companies, $rowArr);
    $companies[] = $rowArr;
}
header('Content-Type: application/json');
$response=array("Companies"=>$companies);
$json = json_encode($response);
echo $json
?>

但问题出在GetCompanies.php文件中,while循环运行无穷无尽。代码似乎没问题。任何帮助,将不胜感激。

4 个答案:

答案 0 :(得分:1)

执行while ($row = $db->getCompanies()) {时,您再次运行整个查询,每次都返回第1行。 mysql_fetch_array会返回一行行。

您需要做的是让getCompanies()遍历所有行并返回一个数组。

public function getCompanies() {    
    $result = mysql_query("SELECT * FROM company");
    // check for successful store

    if ($result) {
        $ret = array();

        while($row = mysql_fetch_assoc($result)){
            $ret[] = $row;
        }

        return $ret;
    } else {
        return false;
    }
}

现在,getCompanies()会返回一个只能foreach结束的数组:

$rows = $db->getCompanies();
foreach($rows as $row){
    // ...
}

答案 1 :(得分:0)

将while循环声明更改为

foreach($rows as $row) {}

正如Pavlin所说,将函数调用移到循环外的getCompanies()。

此外,如何修改查询以从数据库中选择一组特定字段并直接将它们作为响应发送而不进行任何其他处理?

答案 2 :(得分:0)

由于您正在实现不带任何条件的选择查询(where子句)。由于公司表有数据,它总是在while循环中返回true,这使得while循环成为无限循环。为了正常工作,条件应该变为false以退出循环。 它不是一个编程缺陷,它是一个逻辑错误。

答案 3 :(得分:0)

php文档包含您需要的所有信息。你使用了错误的功能:

  

mysqli_fetch_array - 将结果行提取为关联数字   数组或两者

VS

  

mysqli_fetch_all - 将所有结果行作为关联数组获取,a   数组或两者

只需将您的return语句更改为 return mysqli_fetch_all($result); 要么 return mysqli_fetch_all($result, MYSQLI_ASSOC); 获得一个关联数组。

当然,您需要将getCompanies电话转移到循环之外。

注意 从版本5.5开始,php mysql_*函数已被删除。*将很快从语言中删除。您应该查看mysqli_*PDO