Cannot POST data into the database - php

I'm trying to add some data (strings) from my android app using POST. I'm currently testing the code with the Advanced Rest Client however so the imput's from there.
EDIT: To make it more clear what my question is - what's wrong with the code that it doesn't take the values and assign them? why does it skip the first if?
EDIT 2: I am using chrome.google.com/webstore/detail/advanced-rest-client/… to test this POST.
NOTES:
echo #name; -> it does nothing, doesn't echo a thing
Right now, it automatically enters the third else saying that required field(s) are missing.
I've tried using var_dump on $name and it states the following: Unexpected token s => that didn't make any sense.
Thanks in advance for the answers, if you need more info I'll gladly provide it.
This is the code:
$app->post('/users', function() use ($app, $mysql) {
$name = $app->request->post('name');
$email = $app->request->post('email');
$beer_type = $app->request->post('beer_type');
$favorite_beer = $app->request->post('favorite_beer');
$favorite_drink = $app->request->post('favorite_drink');
echo $name;
if (!empty($name) and !empty($email) and !empty($beer_type) and !empty($favorite_beer) and !empty($favorite_drink)) {
$insert = "INSERT INTO clients(name, email) VALUES({$name}, {$email})";
$getid = "SELECT id_client FROM clients WHERE email = {$email}";
$insert2 = "INSERT INTO preferences(client_id, beer_type, favorite_beer, favorite_drink) VALUES({$idvalue}, {$beer_type}, {$favorite_beer}, {$favorite_drink})";
$request = $mysql->query($insert);
$test = false;
$id = 0;
$test2 = false;
if ($request !== false) {
$test = true;
}
if ($test === true) {
$request = $mysql->query($getid);
if ($request !== false) {
$id = $request->fetch_all(MYSQLI_ASSOC);
}
}
if ($id !== 0) {
$request = $mysql->query($insert2);
if ($request !== false) {
$test2 = true;
}
}
if ($test2 === true) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
});

I've solved my issue by changing the java code. I used the Ion Library for the POST and it worked perfectly fine.

Related

Cannot get response from PUT request using Slim Framework

Am trying to update an existing entity in my database using PUT request but i have 2 issues, when am calling the request from phpStorm rest client debugger am getting an error
{"error":true,"message":"Required field(s) restaurant_id, service_rating, food_rating, music_rating is missing or empty"}
when i call the same request from Advance rest client addon on google chrome am getting
{"error":true,"message":"Task failed to update. Please try again!"}
so i can't understand if the real bug is on the verifyRequiredParams or in my function implementation . Am providing the code if someone can help me.
This is my index.php file
$app->put('/userRatings/:rating_id', 'authenticate', function($rating_id) use($app) {
// check for required params
verifyRequiredParams(array('restaurant_id', 'service_rating', 'food_rating', 'music_rating'));
global $user_id;
$restaurant_id = $app->request->put('restaurant_id');
$service_rating = $app->request->put('service_rating');
$food_rating = $app->request->put('food_rating');
$music_rating = $app->request->put('music_rating');
$db = new DbHandler();
$response = array();
// updating rating
$result = $db->updateRating($user_id, $rating_id, $restaurant_id, $service_rating, $food_rating, $music_rating);
if ($result) {
// rating updated successfully
$response["error"] = false;
$response["message"] = "Task updated successfully";
} else {
// task failed to update
$response["error"] = true;
$response["message"] = "Task failed to update. Please try again!";
}
echoRespnse(200, $response);
});
This is the function code for the verifyRequiredParams which is located in the index.php file
function verifyRequiredParams($required_fields) {
$error = false;
$error_fields = "";
$request_params = array();
$request_params = $_REQUEST;
// Handling PUT request params
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
$app = \Slim\Slim::getInstance();
parse_str($app->request()->getBody(), $request_params);
}
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
// Required field(s) are missing or empty
// echo error json and stop the app
$response = array();
$app = \Slim\Slim::getInstance();
$response["error"] = true;
$response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
echoRespnse(400, $response);
$app->stop();
}
}
And this is my DbHandler.php file where the function is located.
public function updateRating( $user_id, $rating_id, $restaurant_id, $service_rating, $food_rating, $music_rating) {
$stmt = $this->conn->prepare("UPDATE user_ratings set service_rating = ?, food_rating = ?, music_rating = ? WHERE user_id = ? AND rating_id = ? AND restaurant_id = ?");
$stmt->bind_param("iiiiii", $user_id , $rating_id, $restaurant_id, $service_rating, $food_rating, $music_rating);
$stmt->execute();
$num_affected_rows = $stmt->affected_rows;
$stmt->close();
return $num_affected_rows > 0;
}
All my connections are ok i have checked them and also my other services are working fine
The two errors was because advance rest client use "PUT" with capital letters and php storm with lower characters even if its written with capital in php storm i notice that by changing "PUT" with "put" in the if statement of verifyRequiredParams function and now its working and updating perfectly
Add bellow code in your index.php file
$app->addBodyParsingMiddleware();

read JSON input in slim framework

i am new to slim framework following a tutorial i managed to get post data to my API.but when i tried to send data as JSON it gives me an error.I tried to accpt JSON request as follows what is the correct syntax to achive this.i get error as Required field(s) name, email, password is missing or empty
$app->post('/login', function() use ($app) {
// check for required params
$json = $app->request->getBody();
$data = json_decode($json, true);
verifyRequiredParams(array('name','email', 'password'));
how i can get json data from a post request in my API from an JSON array like
{
"name":"usertest",
"email":"xxxx#xxx.xxx",
"password":"xxxxxx"
}
can i use verifyRequiredParams(array('name','email', 'password')); and $name = $app->request->post('name'); if request come as a JSON.
To read the request data you can use your $data property. It should be an object so you can use it like this:
$name = $data->name;
$email = $data->email;
EDIT:
Use $data = json_decode($json) instead of $data = json_decode($json, true) to convert the json data to object instead of an associative array.
the problem was with placing my verifyRequiredParams function i think.i fixed the issue from following code in case any one had same issue.
$app->post('/login', function() use ($app) {
if($app->request->headers->get('Content-Type')=='application/json'){
$json = $app->request->getBody();
verifyRequiredParamsjson(array('email','password'),$json);
$data = json_decode($json);
// check for required params
$email = $data->email;
$password = $data->password;
}
else{
// check for required params
verifyRequiredParams(array('email', 'password'));
// reading post params
$email = $app->request->post('email');
$password = $app->request->post('password');
}
$response = array();
$db = new DbHandler();
// check for correct email and password
if ($db->checkLogin($email, $password)) {
// get the user by email
$user = $db->getUserByEmail($email);
if ($user != NULL) {
$response["error"] = false;
$response['name'] = $user['name'];
$response['email'] = $user['email'];
$response['apiKey'] = $user['api_key'];
$response['createdAt'] = $user['created_at'];
} else {
// unknown error occurred
$response['error'] = true;
$response['message'] = "An error occurred. Please try again";
}
}
else{
$response['error'] = true;
$response['message'] = 'Login failed. Incorrect credentials';
}
echoRespnse(200, $response);
});
required parameter check,
function verifyRequiredParams($required_fields) {
$error = false;
$error_fields = "";
$request_params = array();
$request_params = $_REQUEST;
// Handling PUT request params
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
$app = \Slim\Slim::getInstance();
parse_str($app->request()->getBody(), $request_params);
}
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
// Required field(s) are missing or empty
// echo error json and stop the app
$response = array();
$app = \Slim\Slim::getInstance();
$response["error"] = true;
$response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
echoRespnse(400, $response);
$app->stop();
}
}

Weird error while uploading to database

I'm creating app with connection to MySQL Database, I have some working PHP files on my domain already, but now I cannot normally use 1 of PHP files.
The PHP file looks like that :
<?php
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
if(isset($_POST['title']) && isset($_POST['dish']) && isset($_POST['review']) && isset($_POST['rating']) && isset($_POST['database_name']) && isset($_POST['UserKeyID']) && isset($_POST['dishphoto']) && isset($_POST['dishsmallphoto'])) {
$title = $_POST['title'];
$dish = $_POST['dish'];
$review = $_POST['review'];
$rating = $_POST['rating'];
$database_name = $_POST['database_name'];
$UserKeyID = $_POST['UserKeyID'];
$dishphoto = $_POST['dishphoto'];
$dishsmallphoto = $_POST['dishsmallphoto'];
$result = mysql_query("INSERT INTO " . $database_name . "(title, review, rating, dish, dishphoto, dishsmallphoto, UserKeyID) VALUES('$title', '$review', '$rating', '$dish', '$dishphoto', '$dishsmallphoto', '$UserKeyID')");
if ($result) {
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
In logcat there is something like that :
[socket][/] connected
[CDS]rx timeout:0
[CDS]SO_SND_TIMEOUT:0
>doSendRequest
<doSendRequest

php login screen error

<?php
/*
* Following code will update a product information
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['email']) && isset($_POST['pass'])) {
$eml = $_POST['email'];
$pass = $_POST['pass'];
$e = "$eml";
// include db connect class
// connecting to db
$db = new PDO('mysql:host=localhost;dbname=quotes;charset=utf8', 'Sidd');
// mysql update row with matched pid
$result = $db->query("SELECT * FROM user WHERE email='$e'");
// check if row inserted or not
if ($result) {
$response["success"] = 1;
$response["message"] = "Login Successful";
// while($row = $result->fetch(PDO::FETCH_ASSOC)) {
// $response["uid"] = $row["uid"];
// echoing JSON response
echo json_encode($response);
}
else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Error
Android app always return Success=1 and login successful whether the entered Email id is right or wrong! As such whether email id exist in database or not. what am i missing? :/ .................... :(
And Also inform whether the commented code will work?!!
Please help
replace
$result = $db->query("SELECT * FROM user WHERE email='$e'");
if ($result) {....}
with
$result = $db->query("SELECT * FROM user WHERE email='$e'");
$row_count = $result->rowCount(); //number of rows with same email
if($row_count >0) {...}
PDO query method returns object. Object is always compared to true. ALWAYS.
query method can return false but only in case there is an error. But having no values that corresponds to given email is not an error.

mysql query and encoding it in json format

I'm using this simple php code to encode the MySql query result in json format.
But Don't know why it is not giving me the desirable output.
I'm actually trying to get the employee details by entering their 'employee_number'.
<?php
require('DB_Connect.php');
require('config.php');
// check for post data
/*
if (isset($_POST["employee_number"])) {
$employee_name = $_POST['employee_number'];
*/
//get a employee from employee_info table
$result = mysql_query("SELECT *FROM employee_info WHERE employee_number =9876543210");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
echo("Success !! Yoo");
$employee = array();
$employee["employee_number"] = $result["employee_number"];
$employee["employee_name"] = $result["employee_name"];
$employee["flag"]=$result["flag"];
// success
$response["success"] = 1;
// user node
$response["employee"] = array();
array_push($response["employee"], $employee);
// echoing JSON response
echo json_encode($response);
} else {
// no employee found
$response["success"] = 0;
$response["message"] = "No employee found";
// echo no users JSON
echo json_encode($response);
}
}else {
// no employee found
$response["success"] = 0;
$response["message"] = "No employee found";
// echo no users JSON
echo json_encode($response);
}
/*} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
*/
// echoing JSON response
echo json_encode($response);
?>
mysql_query is deprecated. Use mysqli or PDO instead.
make sure you format your query properly *note the spaces
$result = mysql_query("SELECT * FROM employee_info WHERE employee_number = 9876543210");
you could also just echo the $result as your employee array doesn't seem to do anything.
echo json_encode($result);

Categories