来自查询的mysql意外输出

时间:2013-03-30 23:14:34

标签: php mysql

也许我早已习惯使用ORM方法从数据库中提取数据,但我现在正在为我的伙伴编写一个简单的小项目,他不需要MVC的所有额外内容,ORM和以下是以下是我在PHP中构建的类中的查询示例。

$this->sqlstart();
$sql = "select label, setting from ".$this->_settings." where id <= 4";
$query = mysql_query($sql);

$result = array();
while($row = mysql_fetch_array($query))
{
    $result[] = $row;
}
return $result;

return $result的输出是:

Array
(
    [0] => Array
        (
            [0] => Week 1 Pay
            [label] => Week 1 Pay
            [1] => 2995
            [setting] => 2995
        )

    [1] => Array
        (
            [0] => Week 2 Pay
            [label] => Week 2 Pay
            [1] => 2995
            [setting] => 2995
        )

    [2] => Array
        (
            [0] => Week 1 Dates
            [label] => Week 1 Dates
            [1] => 1-15
            [setting] => 1-15
        )

    [3] => Array
        (
            [0] => Week 2 Dates
            [label] => Week 2 Dates
            [1] => 16-31
            [setting] => 16-31
        )

)

它应该是

Array
(
    [0] => Array
        (
            [label] => Week 1 Pay
            [setting] => 2995
        )

    [1] => Array
        (
            [label] => Week 2 Pay
            [setting] => 2995
        )

    [2] => Array
        (
            [label] => Week 1 Dates
            [setting] => 1-15
        )

    [3] => Array
        (
            [label] => Week 2 Dates
            [setting] => 16-31
        )

)

任何人都可以向我指出集合中的其他数据来自何处?

4 个答案:

答案 0 :(得分:5)

您应该使用mysql_fetch_assoc来正确获得结果。它将为您提供关联数组而不是普通数组。

答案 1 :(得分:2)

来自http://php.net/manual/en/function.mysql-fetch-array.php

array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )

MYSQL_ASSOC作为第二个参数传递给刚刚获取关联数组,或者只调用mysql_fetch_assoc()

答案 2 :(得分:2)

您应该能够传入第二个参数,该参数只会输出关联列名称:

while($row = mysql_fetch_array($query, MYSQL_ASSOC))

答案 3 :(得分:0)

mysql_fetch_array返回两种访问值的方法:字段名称索引号。您可以将mysql_fetch_array更改为mysql_fetch_assoc或将代码更改为:

while($row = mysql_fetch_array($query)){
     $result[] = array('label' => $row['label'], 'setting' => $row['setting'];
 }