Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

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
admin
Site Admin
Posts: 45

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

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

Code: Select all

<?php
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");
     exit();
  }

  //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)
  { 
    $post_id=$row['post_id']; 
    $post_time=$row['post_time']; 
    $post_subject=$row['post_subject']; 
    $post_text=$row['post_text']; 

   
    $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;

  echo json_encode($posts,JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);
 
?>
Modify the SELECT query as per your db and column name. Upload this php file to any folder like api and hit example.com/api/index.php and you will get the json data.

Post Reply