REST Api Structure prevents Database access - php

I'm hosting my files hostinger.in and is implementing REST architecture. When I was implementing the codes without REST, I was getting no error. But now it seems I can't access MySql Database. I narrow down possible errors which comes when I try registering a user and it seems the DB is inaccessible. Here are the codes:
public function sendOtp($mobile, $model, $brand, $device, $fingerprint, $hardware){
//Checking for User registration
if (!$this->isUserExists($mobile)) {
$otp = rand(100000, 999999);
$stmt = $this->con->prepare("INSERT INTO user_register(mobile, registered_mobile_model, registered_mobile_brand, registered_mobile_device, registered_mobile_fingerprint, registered_mobile_hardware, otp) values(?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $mobile, $model, $brand, $device, $fingerprint, $hardware, $otp);
$result = $stmt->execute();
$stmt->close();
//If statment executed successfully
if ($result) {
//Returning 0, otp sent
return 0;
} else {
//Returning 1, failed to insert
return 1;
}
} else {
//user exists, update info and sent otp
$otp = rand(100000, 999999);
//Crating an statement
$stmt = $this->con->prepare("UPDATE user_register set otp = ?, registered_mobile_model = ?, registered_mobile_brand = ?, registered_mobile_device = ?, registered_mobile_fingerprint = ?, registered_mobile_hardware = ? WHERE mobile = ?");
//Binding the parameters
$stmt->bind_param("sssssss", $otp, $model, $brand, $device, $fingerprint, $hardware, $mobile);
//Executing the statement
$result = $stmt->execute();
//Closing the statement
$stmt->close();
//If statement executed successfully
if ($result) {
//Returning 0, user insert/update success, otp sent
return 0;
} else {
//Returning 1, failed to insert
return 1;
}
}
}
private function isUserExists($mobile) {
$stmt = $this->con->prepare("SELECT id from user_register WHERE mobile = ?");
$stmt->bind_param("s", $mobile);
$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;
$stmt->close();
return $num_rows > 0;
}
The index.php code to reroute the api calls:
$app->post('/sendotp', function () use ($app) {
//Verifying the required parameters
verifyRequiredParams(array('mobile', 'model', 'brand', 'device', 'fingerprint', 'hardware'));
//Creating a response array
$response = array();
//reading post parameters
$mobile = $app->request->post('mobile');
$model = $app->request->post('model');
$brand = $app->request->post('brand');
$device = $app->request->post('device');
$fingerprint = $app->request->post('fingerprint');
$hardware = $app->request->post('hardware');
//Creating a DbOperation object
$db = new DbOperation();
$res = $db->sendOtp($mobile, $model, $brand, $device, $fingerprint, $hardware);
//If the result returned is 0 means success
if ($res == 0) {
//Making the response error false
$response["error"] = false;
//Adding a success message
$response["message"] = "OTP Sent";
//Displaying response
echoResponse(201, $response);
//If the result returned is 1 means failure
} else if ($res == 1) {
$response["error"] = true;
$response["message"] = "Oops! An error occurred while registering";
echoResponse(200, $response);
}
});

Related

MySql Insert returns null

i have the following function:
public function insertMomentToDB($uid, $type, $data)
{
$stmt = $this->conn->prepare("INSERT INTO moments_newsfeed(user_id, type, time, data) VALUES(?, ?, NOW(), ?)");
$stmt->bind_param("sss", $uid, $type , $data);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result)
{
return true;
}
else
{
return false;
}
}
where $data = json undecoded, i want to put it in json format inside the table
$result is always null so it returns false..

How to insert with a foreign key in the child table php

I have two tables users And requests. Users table has columns: id, username, password and town. I can insert data in users successfully. requests table has: id, user_id, product_name, proposed_price and request_description, where user_id is a foreign key referencing to id from users table. The problem is that insert data fails in requests table which has user_id as a foreign key. I get an error:
Undefined variable: user_id and mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement on line : $qry->bind_param("i", $user_id);
This function is supposed to be used in insertion:
public function User_request ($product_name, $proposed_price, $request_description) {
$qry = $this->conn->prepare("SELECT id FROM users WHERE id = '$user_id' ");
$qry->bind_param("i", $id);
$result= $qry->execute();
$user_id = $qry->num_rows();
$qry->close();
if($user_id > 0){
$stmt = $this->conn->prepare("INSERT INTO requests (user_id, product_name, proposed_price, request_description) VALUES(?, ?, ?, ?)");
$stmt->bind_param("sss",$user_id, $product_name, $proposed_price, $request_description);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM requests WHERE request_description = ?");
$stmt->bind_param("s", $request_description);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
}
And below code calls above function:
<?php
include './DbHandler.php';
$db = new DBHandler();
// json response array
$response = array("error" => FALSE);
if ( isset($_POST['product_name']) && isset($_POST['proposed_price']) && isset($_POST['request_description']) ) {
// receiving the post params
$product_name = $_POST['product_name'];
$proposed_price =$_POST['proposed_price'];
$request_description =$_POST['request_description'];
// create a new request
$user = $db-User_request($product_name, $proposed_price, $request_description);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["user"]["username"] = $user["username"];
$response["user"]["proposed_price"] = $user["proposed_price"];
$response["user"]["request_description"] = $user["request_description"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "oops error occured!";
echo json_encode($response);
}
}
else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters are missing!";
echo json_encode($response);
}
?>
Rewrite User_request() function accordingly:
public function User_request ($product_name, $proposed_price, $request_description) {
$qry = $this->conn->prepare("SELECT id FROM users WHERE id = ? ");
$qry->bind_param("i", $user_id);
$result= $qry->execute();
$user_id = $qry->num_rows();
$qry->close();
if($user_id > 0){
$stmt = $this->conn->prepare("INSERT INTO requests (user_id, product_name, proposed_price, request_description) VALUES(?, ?, ?, ?)");
$stmt->bind_param("isss", $user_id, $product_name, $proposed_price, $request_description);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM requests WHERE request_description = ?");
$stmt->bind_param("s", $request_description);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
}
Note: You supposed to use placeholder ? in prepare statement: $this->conn->prepare("SELECT id FROM users WHERE id = '$user_id' "); in place of '$user_id', since you have $qry->bind_param("i", $user_id).
Similar error in $stmt->bind_param("sss",$user_id, $product_name, $proposed_price, $request_description);, replace "sss" with "isss".
You are looking for the string literal of '$user_id' here.
$qry = $this->conn->prepare("SELECT id FROM users WHERE id = '$user_id' ");
This is probably not what you want. You are also using named placeholders that are nowhere to be found in your query. I suggest reviewing the PDO docs.

Function won't select data from database

I'm working on a new website at the moment and I have a bit of a problem.
I look if an item exist, if it does, it will execute an insert query. The insert query works but the problem is that the select query doesn't work
Class
public function doubt($event_id)
{
$exist = $this->conn->prepare("SELECT * FROM agenda WHERE id=?");
$exist->bind_param('s', $event_id);
$exist->execute();
$exist->get_result();
if($exist->num_rows != null)
{
$now = new DateTime();
$date = $now->getTimestamp();
$status = 2;
$stmt = $this->conn->prepare("INSERT INTO absence (user_id,event_id,status,ip,date) VALUES (?, ?, ?, ?, ?) ");
$stmt->bind_param('sssss', $_SESSION['user_session'], $event_id, $status, $_SERVER['REMOTE_ADDR'], $date);
$stmt->execute();
$stmt->close();
return true;
}
else
{
return false;
}
}

PHP : return last inserted Id on statement

So I want to get and return last inserted id from query.
I am successfully get the last inserted id but I have a little problem when try to return it to index.php file
This is my method code :
public function InsertUserCard(UserCard $uc)
{
if(!$this->DuplicateUserCard($uc))
{
$stmt = $this->conn->prepare("INSERT INTO ".$this->table_name."
(user_id, card_id, barcode, barcode_format, created_at, updated_at)
VALUES(?, ?, ?, ?, ?, ?)");
if ($stmt == FALSE)
{
die($this->conn->error);
}
else
{
$user_id = NULL;
$card_id = NULL;
$barcode = NULL;
$barcode_format = NULL;
$created_at = NULL;
$updated_at = NULL;
$stmt->bind_param("iissss", $user_id, $card_id, $barcode, $barcode_format, $created_at, $updated_at);
$user_id = $uc->getUserId();
$card_id = $uc->getCardId();
$barcode = $uc->getBarcode();
$barcode_format = $uc->getBarcodeFormat();
$created_at = $uc->getCreatedAt();
$updated_at = $uc->getUpdatedAt();
$stmt->execute();
$result = $this->conn->insert_id; <-- This is how I get the last inserted id
$stmt->close();
}
// Check for successful insertion
if ($result)
{
// User card successfully inserted
return USER_CARD_INSERTED_SUCCESSFULLY;
}
else
{
// Failed to insert user card
return USER_CARD_INSERT_FAILED;
}
}
else
{
return USER_CARD_ALREADY_EXISTED;
}
}
and this is my index.php file
$app->post('/user/card/rev', 'authenticate', function() use ($app)
{
// check for required params
verifyRequiredParams(array('user_id', 'card_id', 'barcode', 'barcode_format', 'created_at', 'updated_at'));
global $user_id;
$response = array();
$timestamp = time();
$now = date("Y-m-d H:i:s", $timestamp);
$uc = new UserCard();
$uc->setUserId($user_id);
$uc->setCardId($app->request->post('card_id'));
$uc->setBarcode($app->request->post('barcode'));
$uc->setBarcodeFormat($app->request->post('barcode_format'));
$uc->setCreatedAt($app->request->post('created_at'));
$uc->setUpdatedAt($app->request->post('updated_at'));
// choose card from db by user
$UserCardDB = new UserCardDB(MySqlDb::getInstance()->connect());
$UserCard = $UserCardDB->InsertUserCard($uc);
if ($UserCard == USER_CARD_INSERTED_SUCCESSFULLY)
{
$response["error"] = false;
$response["message"] = "User Card added successfully";
$response["current_timestamp"] = $timestamp;
$response["current_date"] = $now;
$response["last_inserted_id"] = SHOULD_BE_HERE;
echoRespnse(201, $response);
}
});
as you see, I want to put the last inserted id on $response["last_inserted_id"], but I do not know how to do it.
any ideas ?
thanks:)
I think you have your statements backwards
$inserted_id = $this->conn->insert_id;
$result = $stmt->execute();
In prepared statements, execute is what runs your SQL. So you can't get the ID of what hasn't been inserted yet.
$result = $stmt->execute();
$inserted_id = $this->conn->insert_id;
You're also not storing the data anywhere usable ($inserted_id is a local variable to your function). Consider making a class variable like $this->inserted_id and making a function that would return that value.
Try this in you method:
public function InsertUserCard(UserCard $uc)
{
if(!$this->DuplicateUserCard($uc))
{
$stmt = $this->conn->prepare("INSERT INTO ".$this->table_name."
(user_id, card_id, barcode, barcode_format, created_at, updated_at)
VALUES(?, ?, ?, ?, ?, ?)");
if ($stmt == FALSE)
{
die($this->conn->error);
}
else
{
$user_id = NULL;
$card_id = NULL;
$barcode = NULL;
$barcode_format = NULL;
$created_at = NULL;
$updated_at = NULL;
$stmt->bind_param("iissss", $user_id, $card_id, $barcode, $barcode_format, $created_at, $updated_at);
$user_id = $uc->getUserId();
$card_id = $uc->getCardId();
$barcode = $uc->getBarcode();
$barcode_format = $uc->getBarcodeFormat();
$created_at = $uc->getCreatedAt();
$updated_at = $uc->getUpdatedAt();
}
// Check for successful insertion
if ($stmt->execute())
{
$result = $this->conn->insert_id;
$stmt->close();
return $result;
}
else
{
// Failed to insert user card
return USER_CARD_INSERT_FAILED;
}
}
else
{
return USER_CARD_ALREADY_EXISTED;
}
}
and in you index.php:
$app->post('/user/card/rev', 'authenticate', function() use ($app)
{
// check for required params
verifyRequiredParams(array('user_id', 'card_id', 'barcode', 'barcode_format', 'created_at', 'updated_at'));
global $user_id;
$response = array();
$timestamp = time();
$now = date("Y-m-d H:i:s", $timestamp);
$uc = new UserCard();
$uc->setUserId($user_id);
$uc->setCardId($app->request->post('card_id'));
$uc->setBarcode($app->request->post('barcode'));
$uc->setBarcodeFormat($app->request->post('barcode_format'));
$uc->setCreatedAt($app->request->post('created_at'));
$uc->setUpdatedAt($app->request->post('updated_at'));
// choose card from db by user
$UserCardDB = new UserCardDB(MySqlDb::getInstance()->connect());
$UserCard = $UserCardDB->InsertUserCard($uc);
if (($UserCard != "USER_CARD_INSERT_FAILED") and ($UserCard != "USER_CARD_ALREADY_EXISTED"))
{
$response["error"] = false;
$response["message"] = "User Card added successfully";
$response["current_timestamp"] = $timestamp;
$response["current_date"] = $now;
$response["last_inserted_id"] = $UserCard;
echoRespnse(201, $response);
}
});
The way I read that, your // Check for successful insertion section will never run because the function is terminated with return $result; before the conditional. Therefore, USER_CARD_INSERTED_SUCCESSFULLY is never returned.
In my functions, I usually return an array, for example:
$result = array( "status" => $status, "id" => $id );
return $result;
and, in the main:
$result = my_function();
$status = $result['status'];
$id = $result['id'];
I hope this help you!
In your method code instead of using $inserted_id use a $_SESSION variable $_SESSION['inserted_id']. Now you will be able to use this in your index.php
$response["last_inserted_id"] = $_SESSION['inserted_id '];

Insert date in mysql using php mysqli functions

I have this REST api code on backend:
public function createDay($user_id, $day, $startLocation, $startTime) {
$stmt = $this->conn->prepare("INSERT INTO days(day,startLocation,startTime,dayDate) VALUES(?,?,?,?)");
$stmt->bind_param("ssss", $day, $startLocation, $startTime, $dayDate);
$result = $stmt->execute();
$stmt->close();
if ($result) {
// task row created
// now assign the task to user
$new_day_id = $this->conn->insert_id;
$res = $this->createUserDay($user_id, $new_day_id, $dayDate);
if ($res) {
// task created successfully
return $new_day_id;
} else {
// task failed to create
return NULL;
}
} else {
// task failed to create
return NULL;
}
}
and function createDay:
public function createUserDay($user_id, $day_id, $dayDate) {
$stmt = $this->conn->prepare("INSERT INTO user_days(user_id, day_id, $dayDate) values(?, ?, ?)");
$stmt->bind_param("iis", $user_id, $day_id, $dayDate);
$result = $stmt->execute();
if (false === $result) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->close();
return $result;
}
}
this is dbhandler file, now i have a question -
I use
$new_day_id = $this->conn->insert_id;
to get ID of current data but also how I can get $dayDate to use into createUserDay function
So I need to get $dayDate and use it into createUserDay function, is there any way?

Categories