0

I'm using XAMPP and phpMyAdmin to create local databases. Here's my PDO code to try to display some tables

<?php
    $pdo = new PDO('mysql:host=localhost;dbname=puppies', 'admin','puppies');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    try {        
        $result = $pdo->query('SELECT `puppy_name`, `breed_name`, `description`, `price` FROM `animals`, `breeds` WHERE `animals` . `breed_id` = `breeds` . `id`');
    } 
    catch (PDOException $e) {
        echo $e->getMessage();
    }
    foreach ($result as $puppy) {
        $puppy[`puppy_name`]
        $puppy[`breed_name`]
    }
?>

I keep receiving this error:

Parse error: syntax error, unexpected '$puppy' (T_VARIABLE) in /Applications/XAMPP/xamppfiles/htdocs/cs4ww3/invalid.php on line 12

I'm pretty sure I'm connecting properly - if I remove the foreach loop then I get a blank screen with no errors.

Qirel
  • 25,449
  • 7
  • 45
  • 62
Nicholas Hassan
  • 949
  • 2
  • 10
  • 27
  • 5
    `$puppy[\`breed_name\`]` wrong use of quotes (should be single-quotes `'`, not backticks `\``) and missing a `;` at the end there. – Qirel Nov 20 '16 at 22:07
  • 4
    and `echo`, if you want print them. – Federkun Nov 20 '16 at 22:08
  • 2
    What is supposed to be happening inside your `foreach`? – ChrisGPT was on strike Nov 20 '16 at 22:08
  • @Chris I'm trying to print the name of the dog and its breed for each dog (row). The previous two users were right, that I needed to add echo and semicolons and change the backticks. At the moment it all comes out in one long sentence, with each row back-to-back, but I'm just happy I got it to print! – Nicholas Hassan Nov 20 '16 at 22:17
  • 1
    You just need to space it up then ;- ) `echo $puppy['puppy_name']." ".$puppy['breed_name']."
    ";` might get you started on what you want! @NicholasHassan
    – Qirel Nov 20 '16 at 22:31

1 Answers1

1

To have valid code, you first have to add semi colon to each row within your loop. Every statement needs (should) end with semi colon.

But it seems you also want to display them. For that you need to echo them: Add echo in front of the lines and concatenate them with a dot:

echo $puppy[...]." ".$puppy[...]."\r\n";

Replace \r\n with <br> if you test it in a browser. \r\n is a new line symbol

Added from the comments: Also remember to use strings to access array values. Only ' and " are used to define string constants. You have used `. Right way:

$puppy['constant'] 
Mruf
  • 766
  • 7
  • 16