Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

PHP & MYSQL Chrome not recognizing try code??

<?php

try{ $db = new PDO("mysql:host=localhost;dbname=shirts4mike;port=8889","root","root"); $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); $db->exec("SET NAMES 'utf8'"); } catch (Exception $e) { echo "Could not connect to the database."; exit; }

try{ $results = $db->query("SELECT name, price FROM products"); echo "Our query ran successfully."; } catch (Exception $e){ echo "Data could not be retrieved." exit; }

?>

it does not echo ANYTHING.

Am i doing something wrong?

1 Answer

Have you tried adding an echo statement to your first try block? Your second catch statement is missing a semicolon after "retrieved." I tried your code and received a parse error message from that missing semicolon. This worked on my machine (I changed the port number and excluded the password parameter.) I'm using Easy PHP server and MySQL Workbench.

   <?php
        try{
             $db = new PDO("mysql: host = localhost; dbname=shirts4mike; port=3306",               
                 "root"); 
            $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); 
            $db->exec("SET NAMES 'utf8'"); 
            echo "Connected to database."; 
       } catch (Exception $e) { 
            echo "Could not connect to the database."; 
            exit; 
      }

    try{ 
           $results = $db->query("SELECT name, price FROM products"); 
           echo " Our query ran successfully."; 
    } catch (Exception $e){ 
            echo "Data could not be retrieved.";
            exit; 
   }
   ?>

OUTPUT: Connected to database. Our query ran successfully.

thanks