0

Question edited following the comments. It still doesn't work.

Hi there,

I'm trying to learn how PDO works, but my script:

$database = new PDO('mysql:host=localhost;dbname=***', '***', '***');
$query = $database->prepare("SELECT nombre, 
                                    tecnica,
                                    tamanno,
                                    estado FROM obra WHERE anno = ?");
$query->execute(array('2009'));
while ($item = $query->fetch(PDO::FETCH_ASSOC)) {
    $item['nombre'];
}

Prints nothing. If I do:

var_dump($query->fetch())

I get bool(false). After reading lots of examples I can't figure out what I'm doing wrong.

Thanks in advance.

Tae
  • 1,665
  • 5
  • 24
  • 45
  • 2
    try not to use special chars in table/field names. and surround them with ` ` – n00b Mar 08 '11 at 22:54
  • What's with all the empty catch blocks? You're not going to have a valid PDO object in `$database` if the connection fails – Phil Mar 08 '11 at 22:54
  • 3
    You need to tell PDO to actually raise exceptions when an error occurs. See http://stackoverflow.com/questions/3726505/how-to-squeeze-error-message-out-of-pdo – Pekka Mar 08 '11 at 22:55
  • Porfavor evita usar acentos o caracteres especiales en los nombres de las columnas tabla ;) – amosrivera Mar 09 '11 at 01:14
  • what is the output when you execute the same query in phpmyadmin? – Raj Mar 09 '11 at 02:54
  • @emaillenin I don't have phpMyAdmin installed on my localhost, but in the MySQL console I get the data which I want. – Tae Mar 09 '11 at 03:17

1 Answers1

0
while ($item = $query->fetch(PDO::FETCH_ASSOC)) {
    $item['nombre'];
}

Prints nothing.

That's because you're not actually doing anything with $item['nombre']. Try:

while ($item = $query->fetch(PDO::FETCH_ASSOC)) {
    print_r($item);
}

You should get your expected output.

If not, try adding this before your connection is opened:

PDO::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

and make sure that you have display_errors set to true.

Charles
  • 50,943
  • 13
  • 104
  • 142