Last active
December 28, 2015 03:19
-
-
Save robynitp/7434004 to your computer and use it in GitHub Desktop.
Connect MySQL to PHP with PDO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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