1

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.

Gravy
  • 12,264
  • 26
  • 124
  • 193

1 Answers1

2

Open httpd.conf file and Add this line inside :

AddType application/x-httpd-php .php .phtml 

This makes your PHP script execute by PHP interpreter.

Then restart apache server using /etc/init.d/apache2 or httpd restart
GBD
  • 15,847
  • 2
  • 46
  • 50
  • can you please tell your server configuration ? or make small php script & run phpinfo() into it and paste that result over here. – GBD Sep 15 '12 at 09:29
  • Ive not pasted it all, but I think I have pasted the relevant stuff... http://pastebin.com/YKUJK7fn – Gravy Sep 15 '12 at 10:05
  • you got phpinfo() through .php file it means php script parsing or executing on your server. from where you running your PDO related php script ? – GBD Sep 15 '12 at 10:13
  • I created a new file in same folder, and typed . – Gravy Sep 15 '12 at 10:29
  • Ok... I think it is a file specific issue... I just tried to put phpinfo() into the top of that connection code... and it didn't work. See updated question. – Gravy Sep 15 '12 at 10:34