I want to wean myself from the teat of the old mysql extension and am just doing a test PDO connection and simple query on a table in a database. I seem to be able to connect, ('connection successful' echoes out) but that's where the good times end. I have spent way too much time now just trying to get started with PDO.
<?php
$host = 'localhost';
$port = '3306';
$username = 'user';
$password = 'blabla';
$database = 'workslist';
try {
$db = new PDO("mysql:host=$host; port = $port; dbname = $database", $username, $password);
echo 'connection successful<br />';
$query = 'SELECT * FROM main';
$statement = $db->prepare($query);
$statement->execute();
$results = $statement->fetchAll();
$statement->closeCursor();
foreach($results as $r){
echo $r['work'] . '<br />';
}
} catch (PDOException $e) {
echo 'Error!: ' . $e->getMessage() . '<br />';
die();
}
?>
Is there anything wrong with the above?
The database name is 'workslist', the table name is 'main', and 'work' is one of the columns in that table. The PHP version I'm using is 5.3.4, and am using wamp on win7. I ran phpinfo()
and under the PDO heading, the PDO drivers mysql, sqlite are enabled. To be sure the database and table actually exist I've tried it with MySQL and can return rows with the old mysql_fetch_array()
method. I've checked the php.ini file to make sure the "extension=php_pdo..." lines are all uncommented.
cheers
`](http://brainstormsandraves.com/articles/semantics/structure/#br) isn't [semantic](http://webstyleguide.com/wsg3/5-site-structure/2-semantic-markup.html). For production code, make sure you use something more appropriate, such as a paragraph or [list](http://www.w3.org/TR/html401/struct/lists.html) element. Don't use [`or die`](http://www.phpfreaks.com/blog/or-die-must-die) when outputting HTML. You'll get invalid HTML. – outis Dec 03 '11 at 09:38