Insert Data with REST API in PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "test";
//Create Connection
$conn = new mysqli($servername, $username, $password, $database);
//Check Connection
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
Above File is mysqli_conn.php File which is included in below Files.Below File is api-insert.php File.
<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Methods, Authorization, X-Requested-With");
//Above "X-Requested-With" means Whatever values comes for insert in database must with Ajax
$data = json_decode(file_get_contents("php://input"), true);
$name = $data["sname"];
$age = $data["sage"];
$city = $data["scity"];
include("mysqli_conn.php");
$sql = "INSERT INTO students(student_name, age, city) VALUES('{$name}','{$age}','{$city}')";
if ($conn->query($sql) == TRUE) {
echo json_encode(array(
"message" => "Student Record Inserted.",
"status" => true
));
} else {
echo json_encode(array(
"message" => "Student Record Not Inserted.",
"status" => false
));
}
.png)
.png)
Comments
Post a Comment