Las filas de objetos PDO se imprimen dos veces

so I'm designing a web interface for a database but when I try to print the values from a query they come in doubles since they are counting 2 indices for the same value. Anyone know why this is happening?

Código 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>");
        }
    }
}

Y esta es la salida que obtengo:

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

preguntado el 05 de mayo de 13 a las 10:05

Just curious, is you array that multidimensional that you need to nest 2 foreach¿s? -

To be honest this is my first attempt at database querying, I nested 2 foreach's so I can print the key and value for each row entry -

if you print keys in first foreach, wouldn't you achieve the desired result -

You want by the number of the column or by the name? You are basically looking for something called the FETCH_MODE, you can set the default mode as an attribute: php.net/pdo.setattribute (PDO::ATTR_DEFAULT_FETCH_MODE) - As you're new, to PDO please make yourself comfortable with the manual first, e.g. read the introduction of the PDO chapter, then read about all the objects and methods you use in your code while you do so. -

2 Respuestas

intenta usar

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

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

en lugar de usar query

contestado el 05 de mayo de 13 a las 10:05

Im not sure if this would fix your problem but try something like this

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

}

you could refer for some tips here: http://php.net/manual/en/pdostatement.fetch.php

contestado el 05 de mayo de 13 a las 10:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.