Reputation:
I am playing around with php, i wish to make a simple api to save my name
field in database using chrome postman
The is my php code:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with');
header('Cache-Control: max-age=900');
header("Content-Type: application/json"); // tell client that we are sending json data
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$dxname =$_GET['name'];
$sql = "INSERT INTO crudtable(firstname, lastname, email,favjob)
VALUES ('".$dxname."', 'Doe', '[email protected]','coder')";
if ($conn->query($sql) === TRUE) {
echo json_encode("New record created successfully");
// echo "New record created successfully";
} else {
echo json_encode("Some error");
// echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When i am using postman ,
1. the name is not getting saved in db [only hard coded values are being saved]
2. I am not getting echo json_encode("New record created successfully");
once data is saved.
Please help, attaching screenshot of my postman result and how i am passing the name variable
Upvotes: 1
Views: 1938
Reputation: 6650
You are sending data through post method and you are using GET.
Change:
$dxname =$_GET['name'];
To
$dxname =$_POST['name'];
ALso:
if ($conn->query($sql) === TRUE) {
To
if ($result = $conn->query($sql))
{ echo json_encode("New record created successfully");
// echo "New record created successfully";
} else {
echo json_encode("Some error");
// echo "Error: " . $sql . "<br>" . $conn->error;
}
Cannot query MySQL database via PHP
Upvotes: 2
Reputation: 124
Json should be an array.. try this
echo json_encode(array("Success"));
where did you get the $_GET method? can you show us the html page? you can try using
$_POST['name'];
Upvotes: 0