how to create API in php mysql database

how to create API in php mysql database

Creating an API in PHP and MySQL involves a few basic steps:

Define the API endpoints:
Decide on the endpoints for your API, which will define the URLs that your API will be accessed through. Each endpoint will represent a specific action that your API will perform, such as retrieving data or updating records.

Create a database:
Your API will need access to data, so you’ll need to create a MySQL database to store that data. You’ll also need to create tables within the database to organize the data.

Write PHP code to handle the API requests:
You’ll need to write PHP code that handles the requests sent to your API endpoints. This code will connect to your MySQL database and perform the necessary queries to retrieve or update data.

Output data in a format that can be consumed by other applications: Your API will need to output the data it retrieves in a format that can be easily consumed by other applications, such as JSON or XML.

Copy the code

<?php
$conn = mysqli_connect("localhost", "root", "", "api");
$responce = array();
if($conn)
{
  $query =  "select * from testapi";
  $result =  mysqli_query($conn, $query);
   if($result)
     {
      header("Content-Type: JSON");
      $d = 0;
      while($row = mysqli_fetch_assoc($result))
        {
          $responce[$d]['id'] = $row ['id'];
          $responce[$d]['name'] = $row ['name'];
          $responce[$d]['email'] = $row ['email'];
          $d++;
        }
        echo json_encode($responce,JSON_PRETTY_PRINT);
     }
}
else{
  echo "connection fail";
}
?>