I am trying to connect to mySQL using PDO.
Please forgive me if I have made a glaring error - I am just learining...
<?php
try {
$db_conn = new PDO('mysql:host=localhost;dbname=testdatabase','test', 'testpass');
}
catch (PDOException $e) {
echo 'Could not connect to database';
}
$stmt = $db_conn->query('SELECT * FROM PRODUCTS');
while ($row = $stmt->fetch() ) {
echo '<pre>'; print_r($row); echo '<pre>';
}
?>
the output from the browser is as follows:
query('SELECT * FROM PRODUCTS'); while ($row = $stmt->fetch() ) { echo '
'; print_r($row); echo '
';
}
?>
What have I done wrong??? why is PHP not parsing the PHP script?
UPDATE:
If I create a new php file, and run phpinfo(); it works.
If I paste phpinfo() into the top of the above code as follows:
<?php
phpinfo();
echo '<h1>PDO TEST</h1>';
try {
$db_conn = new PDO('mysql:host=localhost;dbname=testdatabase','test', 'testpass');
}
catch (PDOException $e) {
echo 'Could not connect to database';
}
$stmt = $db_conn->query('SELECT * FROM Products');
while ($row = $stmt->fetch() ) {
echo '<pre>'; print_r($row); echo '<pre>';
}
?>
I get the following output:
PDO TEST'; try { $db_conn = new PDO('mysql:host=localhost;dbname=testdatabase','test', 'testpass'); } catch (PDOException $e) { echo 'Could not connect to database'; } $stmt = $db_conn->query('SELECT * FROM Products'); while ($row = $stmt->fetch() ) { echo '
'; print_r($row); echo '
';
}
?>
UPDATE: Problem solved... It was some kind of file encoding issue. It works perfectly when I copy and paste the code into a new file. Very strange.