PHP API - Code
#db.php
<?php
$db = mysqli_connect('localhost','root','','test');
# create.php
<?php
include('db.php');
error_reporting(0);
// CREATE TABLE IF NOT EXISTS `prod` (
//`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
//`product_name` varchar(100) NOT NULL,
//`product_price` int(11) NOT NULL,
//`stock` int(11) NOT NULL,
//`discount` int(11) NOT NULL,
//PRIMARY KEY (`id`)
//) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci COMMENT='product table';
//header('Access-Control-Allow-Origin: *');
//header('Content-Type:application/json *');
//// header("Access-Control-Allow-Credentials: true");
//header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
//header('Access-Control-Max-Age: 1000');
//header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
// Allow requests from any origin
header("Access-Control-Allow-Origin: *");
// Allow specific HTTP methods (e.g., GET, POST, PUT, DELETE)
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
// Allow specific HTTP headers in the request
header("Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token");
// Allow credentials (cookies, HTTP authentication) to be included in cross-origin requests
header("Access-Control-Allow-Credentials: true");
// Set the maximum age (in seconds) for how long the preflight request (OPTIONS) can be cached by the browser
header("Access-Control-Max-Age: 3600");
// Return appropriate headers for preflight requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("HTTP/1.1 200 OK");
exit();
}
// Continue processing your API request here
$data=json_decode(file_get_contents("php://input"));
//debug statements commented
// echo '{"msg":"success"}';
// print_r($data);
// echo $data->product_name;
if ($data->product_name == '')
{
echo json_encode(['status'=>'failed','msg'=>'Product Name not provided']);
}elseif ($data->product_price == '')
{
echo json_encode(['status'=>'failed','msg'=>'Product price not provided']);
}elseif ($data->stock == '')
{
echo json_encode(['status'=>'failed','msg'=>'Product stock not provided']);
}elseif ($data->discount == '')
{
echo json_encode(['status'=>'failed','msg'=>'Product discount not provided']);
}else {
$query = "INSERT INTO prod(product_name,product_price,stock,discount)";
$query .= "values ('$data->product_name','$data->product_price','$data->stock','$data->discount')";
$run = mysqli_query($db, $query);
if ($run) {
echo json_encode(['status' => 'success', 'msg' => 'Data inserted']);
} else {
echo json_encode(['status' => 'failed', 'msg' => 'Something did not go well!, required data missing!']);
}
}
Comments
Post a Comment