Created
August 5, 2018 17:41
-
-
Save locvfx/6441bae26a2f8169042f32764bbc971d to your computer and use it in GitHub Desktop.
How to convert MYSQL data to JSON using PHP
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 | |
| // Initialize variable for database credentials | |
| $dbhost = 'hostname'; | |
| $dbuser = 'username'; | |
| $dbpass = 'password'; | |
| $dbname = 'sakila'; | |
| //Create database connection | |
| $dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname); | |
| //Check connection was successful | |
| if ($dblink->connect_errno) { | |
| printf("Failed to connect to database"); | |
| exit(); | |
| } | |
| //Fetch 3 rows from actor table | |
| $result = $dblink->query("SELECT * FROM actor LIMIT 3"); | |
| //Initialize array variable | |
| $dbdata = array(); | |
| //Fetch into associative array | |
| while ( $row = $result->fetch_assoc()) { | |
| $dbdata[]=$row; | |
| } | |
| //Print array in JSON format | |
| echo json_encode($dbdata); | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment