How to convert mysql query result to json (in PHP)
If you are someone like me who loves javascript and would like to integrate some of that spice into your php workflow, this is for you.
I love working with arrays and json data, and this is how i convert mysql query result to json
The main ingredient is the php extract function which does a clever array to variable converstion (It coverts array keys into variable names and array values into variable value).
- Perfrom your database query
- Fectch the result into an associative array
- Create a key + value with the aid of the extract function
- Covert the resulting array from the above to Json
In my example below, i will be quering a students table which has 5 rows (id, firstName, lastName, Phone, email)
If applied correctly, the reslt of the toJson function from the above code block will look like this
{
"id": "id value",
"firstName": "first name value",
"lastName": "last name value",
"phone": "phone value",
"email": "email value"
}
There are more clever ways to take advantage of the extract function but i am gonna leave it simple.