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.

1
  • 1
    That code looks fine to me. The problem is elsewhere. Commented Sep 15, 2012 at 9:00

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

5 Comments

can you please tell your server configuration ? or make small php script & run phpinfo() into it and paste that result over here.
Ive not pasted it all, but I think I have pasted the relevant stuff... pastebin.com/YKUJK7fn
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 ?
I created a new file in same folder, and typed <?php phpinfo(); ?>.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.