Tuesday, 29 September 2020

PHP MYSQL TO JSON

https://www.opentechguides.com/how-to/article/php/100/mysql-to-json.html

<?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);
 
?>

Result:


[
	{
	"actor_id":"1",
	"first_name":"PENELOPE",
	"last_name":"GUINESS",
	"last_update":"2006-02-15 04:34:33"
	},
	{	
	"actor_id":"2",
	"first_name":"NICK",
	"last_name":"WAHLBERG",
	"last_update":"2006-02-15 04:34:33"
	},
	{
	"actor_id":"3",
	"first_name":"ED",
	"last_name":"CHASE",
	"last_update":"2006-02-15 04:34:33"
	}
]

As you can see, the result is a valid JSON. You may use this in combination with Jquery/AJAX to pass database data to a web application that expects data in JSON.

email mailto: pretext

 <a href="mailto:designoutsourced.com+info@gmail.com?subject=Maklumat%20lanjut%20pakej&body=Hai,%20saya%20berminat%20tahu%20lebi...