Last active
August 29, 2015 14:04
-
-
Save dduleone/6331d330fa44765d75e7 to your computer and use it in GitHub Desktop.
mysqli example
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 | |
| /* | |
| CREATE SCHEMA `test`; | |
| CREATE TABLE `animals` (`name` varchar(255), `color` varchar(255), `sound` varchar(255)); | |
| INSERT INTO `animals` SET `name`='frog', `color`='green', `sound`='ribit'; | |
| INSERT INTO `animals` SET `name`='cow', `color`='white', `sound`='moo'; | |
| */ | |
| $db_params = new stdClass(); | |
| $db_params->host = 'localhost'; | |
| $db_params->user = 'root'; | |
| $db_params->pass = ''; | |
| $db_params->database = 'test'; | |
| $db_params->select = 'SELECT * FROM `animals`'; | |
| $db = mysqli_init(); | |
| if (!$db->real_connect($db_params->host, $db_params->user, $db_params->pass, $db_params->database)) { | |
| die('Failed to connect to MySQL: ' . $db->error); | |
| } | |
| if ($result_set = $db->query($db_params->select)) { | |
| $results = array(); | |
| while ($result = $result_set->fetch_assoc()) { | |
| $row = array(); | |
| foreach($result as $col => $value) { | |
| $row[$col] = $value; | |
| } | |
| $results[] = $row; | |
| } | |
| } | |
| echo json_encode($results, JSON_PRETTY_PRINT) . "\n"; | |
| /* | |
| [ | |
| { | |
| "name": "frog", | |
| "color": "green", | |
| "sound": "ribit" | |
| }, | |
| { | |
| "name": "cow", | |
| "color": "white", | |
| "sound": "moo" | |
| } | |
| ] | |
| */ |
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 | |
| $db_params = new stdClass(); | |
| $db_params->host = "localhost"; | |
| $db_params->user = "Matt"; | |
| $db_params->pass = ""; | |
| $db_params->database = "parks"; | |
| $db_params->query = "SELECT * FROM currentQueue ORDER BY arrive ASC"; | |
| $db = mysqli_init(); | |
| $conn = $db->real_connect($db_params->host, | |
| $db_params->user, | |
| $db_params->pass, | |
| $db_params->database); | |
| if (!$conn) { | |
| die("Failed to connect to MySQL: " . $db->error); | |
| } | |
| $query = $db->query($db_params->query); | |
| if(!$query) { | |
| return; | |
| } | |
| $results = array(); | |
| foreach ($query->fetch_all(MYSQLI_ASSOC) as $row) { | |
| $rowArray = array(); | |
| foreach ($row as $col => $value) { | |
| $rowArray[$col] = $value; | |
| } | |
| $results[] = $rowArray; | |
| } | |
| echo json_encode ($results, JSON_PRETTY_PRINT) . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment