mysql只提取单行而不是全部

时间:2014-12-02 15:08:31

标签: php mysql

您好我的PHP代码mysql只取1个结果,这是最后一个而不是全部请帮助我为什么这样做这里是我的代码

        $requesthost = "SELECT * FROM tblvhost";
        $reshost = mysql_query($requesthost);
        while($rowhost=mysql_fetch_array($reshost)) {
            $hostvid = $rowhost['vh_id'];
            $hostname = $rowhost['vh_name'];        
        }

3 个答案:

答案 0 :(得分:1)

你在每次循环迭代中覆盖数据:

    while($rowhost=mysql_fetch_array($reshost)) {
        $hostvid = $rowhost['vh_id'];    // overwritten
        $hostname = $rowhost['vh_name']; // overwritten       
    }

收集您可能想要将它们附加到数组的所有数据:

    $hostvid = array();
    $hostname = array();
    while($rowhost=mysql_fetch_array($reshost)) {
        $hostvid[] = $rowhost['vh_id'];    // insert into array
        $hostname[] = $rowhost['vh_name']; // insert into array       
    }

答案 1 :(得分:0)

您将在循环中覆盖变量。将它们存储在一个数组中。

while ($rowhost = mysql_fetch_array($reshost)) {
    $row[] = array(
        'hostvid' => $rowhost['vh_id'],
        'hostname' => $rowhost['vh_name']
    );
}
var_dump($row);

答案 2 :(得分:0)

这是一个很好的问题,还有一个针对这类问题的新问题的学习曲线

你是代码

$requesthost = "SELECT * FROM tblvhost";
$reshost = mysql_query($requesthost);
while($rowhost=mysql_fetch_array($reshost)) {
    $hostvid = $rowhost['vh_id'];
    $hostname = $rowhost['vh_name'];        
}

看起来不错,但你在做什么或者你如何应用hostvid?或主机名?你可以做到

    while($rowhost=mysql_fetch_array($reshost)) {
        $rowhost['vh_id'];    //do something with the var that's getting mysql field data
        $rowhost['vh_name'];  //same applies here. using $rowhost will continue to to provide data depending on what you have in the db. so you're OK.       
    }

如果您想将数据存储在数组中以供以后在循环外使用,您可以按照@mudasobwa发布的内容进行操作。好答案。