How to create REST API using MySQL to PHP to JSON?

For all PHP related discussion, one of the most popular programming languages on the web.
Post Reply
Site Admin
Posts: 44

How to create REST API using MySQL to PHP to JSON?

Post by admin » Sat Aug 24, 2019 2:23 am


Code: Select all

header("Access-Control-Allow-Origin: *"); 
// Initialize variable for database credentials
$dbhost = 'localhost';
$dbuser = 'yourdbuser';
$dbpass = 'yourdbpassword';
$dbname = 'yourdbname';

  //Create database connection
  $dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

  //Check connection was successful
  if ($dblink->connect_errno) {
     printf("Failed to connect to database");

  //Fetch 3 rows from actor table
  $result = $dblink->query("SELECT post_id, post_time, post_subject, post_text FROM phpbb_posts");
  //store the entire response
  $response = array();
  //the array that will hold the titles and links
  $posts = array();
  while($row=$result->fetch_assoc()) //mysql_fetch_array($sql)

    $posts[] = array(
        'id'=> $post_id, 
        'time'=> date('l jS \of F Y h:i:s A', $post_time), 
        'subject'=> $post_subject, 
        'text'=> $post_text
  //the posts array goes into the response
  $response['posts'] = $posts;

Modify the SELECT query as per your db and column name. Upload this php file to any folder like api and hit and you will get the json data.

Post Reply