Skip to content

Instantly share code, notes, and snippets.

@robynitp
Last active December 28, 2015 03:19
Show Gist options
  • Save robynitp/7434004 to your computer and use it in GitHub Desktop.
Save robynitp/7434004 to your computer and use it in GitHub Desktop.
Connect MySQL to PHP with PDO
<?php
//For more info, see: http://us1.php.net/manual/en/pdo.construct.php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=mysql.yourdomain.com';
$user = 'dbuser';
$password = 'dbpass';
try {
// create PDO object (stands for PHP Data Object, fyi)
$pdo = new PDO($dsn, $user, $password);
echo "Connected!";
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
// write query
$sql = 'SELECT * FROM blog_posts';
// run the query, and get a PDOStatement Object
$statement = $pdo->query($sql);
//fetch the results
$results = $statement->fetchAll();
//iterate through the results
foreach($results as $row){
echo '<h2>';
echo $row['title'];
echo '</h2>';
echo '<p>';
echo $row['body'];
echo "</p>\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment