PHP is a programming language that is widely used to create dynamic websites. MySQL is a database that stores data in tables. In this article, we will show you how to create a simple API in PHP with a MySQL database.
First, you will need to create a MySQL database and table. In the database, you will need to create a table called “users”. The table will have the following fields:
id
username
password
Next, you will need to create a PHP file called “api.php”. The file will contain the following code:
connect(‘localhost’, ‘username’, ‘password’);
$query = “SELECT id, username, password, email FROM users”;
$result = $db->query($query);
if ($result->num_rows > 0) {
echo “
API Results
“;
echo “
ID | Username | Password | |
---|---|---|---|
“.$row[‘id’].” | “.$row[‘username’].” | “.$row[‘password’].” | “.$row[’email’].” |
“;
} else {
echo “
API Error
“;
echo “An error occurred while retrieving data from the database.”;
}
?>
The code above connects to a MySQL database and retrieves data from the “users” table. If the data is found, the code will print it out in a table. If the data is not found, the code will print out an error message.
You can test the API by opening the “api.php” file in a web browser.