Week 3 - PHP Mysql Json
Week 3 - PHP Mysql Json
Week 3 - PHP Mysql Json
LESSON 3
WHAT IS MYSQL DATABASE?
• Create a database.
CONVERTING DATA FROM MYSQL TO JSON
FORMAT
2. Create a table and insert data
Here is a SQL script. Encode and run these SQL commands to create a table named tbl_employee and insert data into the
table.
See SCRIPT at the NOTES section.
CONVERTING DATA FROM MYSQL TO JSON
FORMAT
3. Create a PHP File and make
connection to mysql database
• Create a Project in Netbeans/PHPStorm
IMPORTANT NOTE: Change the value of localhost, username, password and database
name according to your settings.
CONVERTING DATA FROM MYSQL TO JSON
FORMAT
5. Fetch Data from MySQL Database
After opening the connection, fetch the required table data from mysql db. Using the php function mysqli_query(),
I'm going to fetch all the rows from the table 'tbl_employee’. Just copy the following codes highlighted in box.
CONVERTING DATA FROM MYSQL TO JSON
FORMAT
6. Convert MySQL Result Set to PHP Array
Next loop through the mysql result set we got from step-5 and convert it to php array. Just copy the
following codes highlighted in box.
CONVERTING DATA FROM MYSQL TO JSON
FORMAT
7. Convert PHP Array to JSON String
Next use the PHP function json_encode() to convert the php array to json string. Learn about using php
json_decode() function here.
CONVERTING DATA FROM MYSQL TO JSON
FORMAT
8. Close the mysqli connection
You should always close the connection after fetching all the information from the database.
Complete Code
Run the code and you get an output something like this:
CONVERT MYSQL TO JSON FILE IN PHP
If you want to write the data from mysql to json file, add this piece of code at the end instead of
'echo' statement.
ACTIVITY #3 LINK:
https://forms.gle/g5Qpwcj8ttdZ7MtH6