PDO对象行打印两次

时间:2013-05-05 09:02:57

标签: php pdo

所以我正在设计一个数据库的Web界面,但是当我尝试打印查询中的值时,它们会出现双打,因为它们计算相同值的2个索引。任何人都知道为什么会这样吗?

PHP代码:

function loadTable()
{
    $name  = $_GET["table"];
    $db    = new PDO("mysql:host=localhost;dbname=university", "root", "");
    $query = "SELECT * FROM ".$name;
    $rows  = $db->query($query);

    foreach ($rows as $row)
    {
        foreach ($row as $key => $value)
        {
      print ($key.":".$value."<br>");
        }
    }
}

这是我得到的输出:

FM_ID:1234
0:1234
LAST_NAME:
1:
FIRST_NAME:
2:
OFFICE:Bliss 200
3:Bliss 200
EXTENSION:4455
4:4455
HOME_PHONE:5726952
5:5726952
MOBILE_PHONE:71283509
6:71283509
ADDRESS:
7:
EMAIL:
8:
STARTING_YEAR:2011
9:2011
TERMINATION_YEAR:2014
10:2014
LATEST_DEGREE:CMPS
11:CMPS
OBTAINED_FROM:AUB
12:AUB
DEGREE_YEAR:2014
13:2014
RESEARCH_INTEREST:Robotics
14:Robotics

2 个答案:

答案 0 :(得分:4)

尝试使用

$sth = $db->prepare($sql);
$sth->execute();

$rows = $sth->fetchAll(PDO::FETCH_COLUMN);

改为使用query

答案 1 :(得分:4)

我不确定这是否可以解决你的问题,但尝试这样的事情

$result_query = $db->query($query);
while($row = $result_query->fetch(PDO::FETCH_ASSOC)))
{

}

您可以在此处参考一些提示:http://php.net/manual/en/pdostatement.fetch.php