Skip to content

Instantly share code, notes, and snippets.

@johnmorris
Created December 15, 2014 15:22
Show Gist options
  • Save johnmorris/7a5d6c580b7d50aaf058 to your computer and use it in GitHub Desktop.
Save johnmorris/7a5d6c580b7d50aaf058 to your computer and use it in GitHub Desktop.
GET data from a MySQL database with PHP using PDO and MySQLi
<?php
// Be sure to input YOUR database details below
// Watch the associated videos here: https://www.youtube.com/playlist?list=PLLs69n7Q4dCx5_7ZwnxTymH8X0iRP_2vw
$db_user = 'DB USERNAME HERE';
$db_pass = 'DB PASSWORD HERE';
$db_name = 'DB NAME HERE';
$db_host = 'localhost';
// MySQLi
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$result = $mysqli->query("SELECT * FROM objects");
while($row = $result->fetch_object()) {
$results[] = $row;
}
print_r($results);
$result->close();
// PDO
//try {
// $conn = new PDO("mysql:host={$db_host};dbname={$db_name}", $db_user, $db_pass);
// $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// $query = $conn->query("SELECT ID, post_title, post_date FROM objects ORDER BY post_date");
//
// while($row = $query->fetch(PDO::FETCH_OBJ)) {
// $results[] = $row;
// }
//
// print_r($results);
//} catch(PDOException $e) {
// echo 'ERROR: ' . $e->getMessage();
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment