On backend I have rest api, the code is:
$app->get('/tasks', 'authenticate', function() {
global $user_id;
$response = array();
$db = new DbHandler();
// fetch task
$result = $db->getAllUserTasks($user_id);
$result = $db->getAllUserTasks($user_id);
if ($result != NULL) {
$response["error"] = false;
$response["id"] = $result["id"];
$response["task"] = $result["task"];
$response["status"] = $result["status"];
$response["createdAt"] = $result["created_at"];
echoRespnse(200, $response);
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
and with this code I get just first data from array:
{
error: false
id: 2
task: "Create something"
status: 0
createdAt: "2014-12-01 01:58:42"
}
now when I want to fetch all data I write:
if ($result != NULL) {
foreach ($result as $rez) {
$response["error"] = false;
$response["id"] = $rez["id"];
$response["task"] = $rez["task"];
$response["status"] = $rez["status"];
$response["createdAt"] = $rez["created_at"];
echoRespnse(200, $response);
}
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
so the same code with foreach loop but then I get: Unexpected token {
What is wrong with that? How I can implement here WHILE loop instead foreach ???
UPDATE with function:
public function getAllUserTasks($user_id) {
$stmt = $this->conn->prepare("SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?");
$stmt->bind_param("i", $user_id);
if ($stmt->execute()) {
$res = array();
$stmt->bind_result($id, $task, $status, $created_at);
// TODO
// $task = $stmt->get_result()->fetch_assoc();
$stmt->fetch();
$res["id"] = $id;
$res["task"] = $task;
$res["status"] = $status;
$res["created_at"] = $created_at;
$item[] = $res;
$stmt->close();
return $item;
} else {
return NULL;
}
}
Store the results as an array and send the entire array when the loop ends:
if ($result != NULL) {
$items = array();
foreach ($result as $rez) {
$response["error"] = false;
$response["id"] = $rez["id"];
$response["task"] = $rez["task"];
$response["status"] = $rez["status"];
$response["createdAt"] = $rez["created_at"];
$items[] = $response;
}
echoRespnse(200, $items);
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
And echoRespnse() should json_encode the $items array.
Also, in your getAllUserTasks() function, you should use a while loop to fetch all the results from db:
if ($stmt->execute()) {
$items = $res = array();
$stmt->bind_result($id, $task, $status, $created_at);
// fetch values
while ($stmt->fetch()) {
$res["id"] = $id;
$res["task"] = $task;
$res["status"] = $status;
$res["created_at"] = $created_at;
$items[] = $res;
}
$stmt->close();
return $items;
} else {
return NULL;
}
Related
How I can let user login from android app, using codeigniter api.
JSON response..
I want use password_hash and password_verify method for more security.
I tryed to password_verify in model, but getting error 1 wrong password. If I debug my app I can see it tries to post password what is not encrypted, but I think this password must be checked in Model.
controller:
public function login() {
$response = array("success" => 0, "error" => 0);
if (isset($_POST['email']) && $_POST['email'] != '') {
$device_token = $_POST['device_token'];
$email = $_POST['email'];
$password = $_POST['password'];
$device_type = $_POST['device_type'];
$data = $this->Registration_model->login($email,$password,$device_token,$device_type);
if ($data) {
$user_id = $data['u']->id;
$status_level = $this->Freelancer_model->service_level($user_id);//Bronze,silver..
$discount = $this->Registration_model->discountDetails($user_id);
if (!empty($discount)) {
$discount = $discount;
} else {
$discount ='';
}
if ($data['u']->approve_status == 1) {
$response["error"] = 0;
$response["success"] = 1;
$response["message"] = "success";
$image = base_url().'upload/'.$data['u']->user_image;
$response["data"]["user_id"] = $data['u']->id;
$response["data"]["user_image"] = $image;
$response["data"]["user_type"] = $data['u']->user_type;
$response["data"]["referral_code"] = $data['u']->referral_code;
$response["data"]["device_token"] = $data['u']->device_token;
$response["data"]["company_name"] = $data['u']->company_name;
$response["data"]["reg_no"] = $data['u']->registration_no;
$response["data"]["first_name"] = $data['u']->first_name;
$response["data"]["last_name"] = $data['u']->last_name;
$response["data"]["dob"] = $data['u']->dob;
$response["data"]["address"] = $data['u']->address;
$response["data"]["lat"] = $data['u']->lat;
$response["data"]["long"] = $data['u']->long;
$response["data"]["mobile"] = $data['u']->mobile;
$response["data"]["email"] = $data['u']->email;
$response["data"]["password"] = $data['u']->password;
$response["data"]["gender"] = $data['u']->gender;
$response["data"]["about"] = $data['u']->about;
$response["data"]["address_acceptance"] = $data['u']->address_acceptance;
$response["data"]["availability"] = $data['u']->availability;
$response["data"]["canceling_policy"] = $data['u']->canceling_policy;
$response["data"]["acceptance"] = $data['u']->acceptance;
$response["data"]["seen_status"] = $data['u']->seen_status; // 0=not, 1=yes
$response["data"]["approv_status"] = $data['u']->approve_status;
$response["data"]["complete_serviceLevel"]= $status_level;
$response["account"] = $data['a'];
$response["discount"] = $discount;
echo json_encode($response);
} else {
$response["error"] = 2;
$response["success"] = 0;
$response["message"] = "User is not approved";
echo json_encode($response);
}
} else {
$response["error"] = 1;
$response["success"] = 0;
$response["message"] = "Enter correct email and password";
echo json_encode($response);
}
} else {
$response["error"]=4;
$response["message"]= "Access denied";
echo json_encode($response);
}
}
model:
public function login($email, $password, $device_token, $device_type) {
$r = $this->db->get_where('registration', array('email'=>$email, 'password'=>$password));
$count = $r->num_rows();
if ($count > 1) {
$this->db->select('id,email,user_type');
$this->db->from('registration');
$this->db->where('email',$email);
$cc = $this->db->get()->result();
$response["error"] = 0;
$response["success"] = 1;
$response["message"] = "Success, Which account does you want to login?";
$response["data"] = $cc;
echo json_encode($response);
die();
} else if ($count == 1) {
$r1 = $r->row();
$id = $r1->id;
$this->db->where('id',$id);
$update =$this->db->update('registration',array('device_token' => $device_token,'device_type' => $device_type));
//$id = $r1->id;
$r2 = $this->db->get_where('accountdetails', array('user_id' => $id))->result();
$data= array(
"u" =>$r1,
"a" =>$r2
);
return $data;
} else {
return false;
}
}
How to add http response status to rest api in slim framework. In this code i have to fetch values through database if no data found it will show http status response
<?php
$app->get('/api/view', function() {
//call connection file
require_once('dbconnect.php');
//array for JSON response
$query = "select * from firm order by firmId";
$result = $mysqli->query($query);
// code node
while($row = $result->fetch_assoc())
{
// temp user array
$data[] = $row;
}
if (isset($data))
{
header('Content-Type: application/json');
echo json_encode($data);
}
});
//display single row
$app->get('/api/view/{firmId}', function($request, $response) {
require_once('dbconnect.php');
$firmId = $request->getAttribute('firmId');
$query = "select * from firm where firmId = $firmId";
$result = $mysqli->query($query);
$data[] = $result->fetch_assoc();
header('Content-Type: application/json');
echo json_encode($data)."</br>" ."</br>";
});
here i post some function to get response status and one api example to echo response... hope it helpfull.
function verifyRequiredParams($required_fields) {
$error = false;
$error_fields = "";
$request_params = array();
$request_params = $_REQUEST;
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) {
$response = array();
$app = \Slim\Slim::getInstance();
$returncode = "3";
$returnmessage = 'Some Fields Are Empty, Required
field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
$response['returncode'] = $returncode;
$response['returnmessage'] = $returnmessage;
$response['returndatacount'] = 0;
$response['returndata'] = array();
echoRespnse(400, $response);
$app->stop();
}
}
function echoRespnse($status_code, $response) {
$app = \Slim\Slim::getInstance();
$app->status($status_code);
$app->contentType('application/json');
echo json_encode($response);
}
function authenticate(\Slim\Route $route) {
$headers = apache_request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
if (isset($headers['BLAuth'])) {
$db = new BLICKXDbHandler();
$api_key = $headers['BLAuth'];
if (!$db->isValidApiKey($api_key)) {
$returncode = "4";
$returnmessage = "Authentication Fail, Wrong
Authorization Header Define";
$response['returncode'] = $returncode;
$response['returnmessage'] = $returnmessage;
$response['returndatacount'] = 0;
$response['returndata'] = array();
echoRespnse(200, $response);
$app->stop();
} else {
}
} else {
$returncode = "4";
$returnmessage ="Authentication Fail, No Authorization
Header Define";
$response['returncode'] = $returncode;
$response['returnmessage'] = $returnmessage;
$response['returndatacount'] = 0;
$response['returndata'] = array();
echoRespnse(200, $response);
$app->stop();
}
}
$app->post('/getinfo', 'authenticate', function() use ($app) {
verifyRequiredParams(array('usertype'));
$usertype = $app->request()->post('usertype');
$response = array();
$db = new BLICKXDbHandler();
$result = array();
if(isset($usertype) && $usertype=="fr")
{
$result = $db->getFranchisedetails();
}
else if(isset($usertype) && $usertype=="op")
{
$result = $db->getOperatordetails();
}
if(count($result)==0)
{
$returncode = "1";
$returnmessage = "No Data Found";
$response['returncode'] = $returncode;
$response['returnmessage'] = $returnmessage;
$response['returndatacount'] = 0;
$response['returndata'] = array();
}
else
{
$response = array();
$returncode = "0";
$returnmessage = "Data Listed Sucessfully";
$alldata = array();
$kk=0;
if(isset($usertype) && $usertype=="fr")
{
foreach ($result as $key => $task) {
$franchise_id = $task["franchise_id"];
$franchise_name = $task["franchise_name"];
$alldata[$kk]['id'] = $franchise_id;
$alldata[$kk]['name'] = $franchise_name;
$kk++;
}
}
You can Just Use your response object to return json data and http status
even without adding the content type header, It will be added by your response object.
$app->get('/api/view', function() {
//call connection file
require_once('dbconnect.php');
//array for JSON response
$query = "select * from firm order by firmId";
$result = $mysqli->query($query);
// code node
while($row = $result->fetch_assoc())
{
// temp user array
$data[] = $row;
}
if (isset($data))
{
//header('Content-Type: application/json');
//echo json_encode($data);
//send json data wih http status
return $response->withJson($data,200);
//Where 200 is the http status
}
else{
$message=array("message"=>"empty data")
return $response->withJson($message,404);
//Where 404 is not found http status for example
}
});
I'm trying to get all users from users table and return response as JSON but I'm getting error of table is empty all the time even when there are data on the table.
My code:
<?php
include './include/DbHandler.php';
$db = new DbHandler();
$response = array();
// fetching all users
$result = $db->getAllUsers();
if($result != NULL){
$response["error"] = false;
$response["users"] = array();
// looping through result and preparing users array
while ($user = $result->fetch_assoc()) {
$tmp = array();
$tmp["user_id"] = $user["id"];
$tmp["first_name"] = $user["first_name"];
$tmp["last_name"] = $user["last_name"];
$tmp["mobile"] = $user["mobile"];
$tmp["fcm_token"] = $user["token"];
array_push($response["users"], $tmp);
}
} else {
$response["error"] = true;
$response["message"] = "No users found on DB";
}
echo json_encode($response);
?>
The getAllUsers function:
public function getAllUsers(){
$stmt = $this->conn->prepare("SELECT u.id, u.first_name, u.last_name, u.mobile, u.token FROM users u");
if($stmt->execute()){
if($stmt->num_rows > 0){
$users = $stmt->get_result();
$stmt->close();
return $users;
} else {
return NULL;
}
} else {
return NULL;
}
}
try this
$stmt = $this->conn->prepare("SELECT u.id, u.first_name, u.last_name, u.mobile, u.token FROM users u");
if($stmt->execute()){
$stmt->store_result();
if($stmt->num_rows > 0){
$users = $stmt->get_result();
$stmt->close();
return $users;
} else {
return NULL;
}
} else {
return NULL;
}
in getAllUsers Function (add $stmt->store_result() before if(stmy_num-rows)
http://php.net/manual/fr/mysqli-stmt.num-rows.php
Try using,
$stmt->fetch();
Instead of,
$stmt->get_result();
Also please refer this link, which is exact issue which you're facing after the tweak. Getting only 2 records,
Fetch proper data returning only 2 records
Try this. This will resolve your issue.
public function getAllUsers(){
$stmt = $this->conn->prepare("SELECT u.id, u.first_name, u.last_name, u.mobile, u.token FROM users u");
if($stmt->execute()){
$stmt->store_result();
if($stmt->num_rows > 0){
$stmt->bind_result($col1, $col2, $col3, $col4, $col5);
while ($stmt->fetch()) {
printf("%s %s\n", $col1, $col2, $col3, $col4, $col5);
}
$stmt->free_result();
$stmt->close();
} else {
return NULL;
}
} else {
return NULL;
}
}
You have to use bind_result. please check the link why i use this http://php.net/manual/en/mysqli-stmt.bind-result.php
something like this
public function getAllUsers(){
$stmt = $this->conn->prepare("SELECT u.id, u.first_name, u.last_name, u.mobile, u.token FROM users u");
if($stmt->execute()){
if($stmt->num_rows > 0){
if($stmt->get_result() != NULL){
$response["error"] = false;
$response["users"] = array();
// looping through result and preparing users array
while ($user = $stmt->fetch_assoc()) {
$tmp = array();
$tmp["user_id"] = $user["id"];
$tmp["first_name"] = $user["first_name"];
$tmp["last_name"] = $user["last_name"];
$tmp["mobile"] = $user["mobile"];
$tmp["fcm_token"] = $user["token"];
array_push($response["users"], $tmp);
}
} else {
$response["error"] = true;
$response["message"] = "No users found on DB";
}
$stmt->close();
return $response;
} else {
$stmt->close();
return NULL;
}
} else {
$stmt->close();
return NULL;
}
}
i want to add manual magento login and registration webservice for my android project. and how to do that with the help of php? i've tried these steps for login
<?php
class My_Module_Controller extends Mage_Core_Controller_Front_Action {
public function indexAction() {
// if customer is not logged in
if(!Mage::getSingleton('customer/session')->isLoggedIn())
{
// get the email and load the customer by id
$login = $this->getRequest()->getPost('login');
$email = $login['hi#gmail.com'];
$customer = Mage::getModel('customer/customer')
->setWebsiteId(Mage::app()->getStore()
->getWebsiteId())->loadByEmail($email);
$quote = Mage::getSingleton('checkout/cart')->getQuote();
//If the customer exists, log them in by forwarding to loginPost
if($customer->getId())
{
// just make the customer log in
$mysession = Mage::getSingleton('customer/session');
$mysession->setBeforeAuthUrl(Mage::getUrl('checkout/cart'));
$mysession->setAfterAuthUrl(Mage::getUrl('checkout/cart'));
$this->_forward('login','account','customer');
}
else
{
//There is no customer with that email.
}
}
$this->_redirect('checkout/cart');
return;
}
}
?>
and this for registration
public function indexAction()
{
$this->loadLayout();
$this->renderLayout();
}
public function loginAction()
{
$session = Mage::getSingleton('customer/session');
if ($session->isLoggedIn()) {
// is already login redirect to account page
return;
}
$result = array('success' => false);
if ($this->getRequest()->isPost())
{
$login_data = $this->getRequest()->getPost('login');
if (empty($login_data['username']) || empty($login_data['password'])) {
$result['error'] = Mage::helper('onepagecheckout')->__('Login and password are required.');
}
else
{
try
{
$session->login($login_data['username'], $login_data['password']);
$result['success'] = true;
$result['redirect'] = Mage::getUrl('*/*/index');
}
catch (Mage_Core_Exception $e)
{
switch ($e->getCode()) {
case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
$message = Mage::helper('onepagecheckout')->__('Email is not confirmed. Resend confirmation email.', Mage::helper('customer')->getEmailConfirmationUrl($login_data['username']));
break;
default:
$message = $e->getMessage();
}
$result['error'] = $message;
$session->setUsername($login_data['username']);
}
}
}
$this->_redirect('customer/account/');
//$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
}
but i am unable to do it.and how can i make it run
I took this code from net by googling it
For login
$websiteId = Mage::getModel('core/store')->load($store)->getWebsiteId();
$res = array();
$res["username"] = $username;
$res["password"] = base64_decode($password);
$login_status = 1;
try{
$login_customer_result = Mage::getModel('customer/customer')->setWebsiteId($websiteId)->authenticate($username, base64_decode($password));
$login_customer = Mage::getModel('customer/customer')->setWebsiteId($websiteId);
$login_customer->loadByEmail($username);
$res["firstname"] = $login_customer->firstname;
$res["lastname"] = $login_customer->lastname;
$res["id"] = $login_customer->getId();
//$res["password"]
//$res["password"]
}
catch( Exception $e ){
$login_status = 0;
}
$res["login_status"] = $login_status;
return $res;
Fir registration
$res = array();
$websiteId = Mage::getModel('core/store')->load($store)->getWebsiteId();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setCurrentStore($store);
// echo 'Phase 2';
try {
// If new, save customer information
$customer->firstname = $firstname;
$customer->lastname = $lastname;
$customer->email = $email;
$customer->password_hash = md5(base64_decode($password));
$res["email"] =$email;
$res["firstname"] =$firstname;
$res["lastname"] =$lastname;
$res["password"] =$password;
$res["status"] = 0;
$res["id"] = 0;
$cust = Mage::getModel('customer/customer')
->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
->loadByEmail($email);
//check exists email address of users
if ($cust->getId()) {
$res["id"] = $cust->getId();
$res["status"] = 0;
}else {
//echo 'Phase 2.5';
if($customer->save()){
$customer->sendNewAccountEmail('confirmed');
$this->send_Password_Mail_to_NewUser($firstname, base64_decode($password), $email);
$res["id"] = $customer->getId();
$res["status"] = 1;
}
else{
//echo "Already Exist";
$exist_customer = Mage::getModel("customer/customer");
$exist_customer->setWebsiteId($websiteId);
$exist_customer->setCurrentStore($store);
$exist_customer->loadByEmail($email);
$res["id"] = $exist_customer->getId();
$res["status"] = 1;
//echo "An error occured while saving customer";
}
}
//echo 'Phase 3';
}
catch(Exception $e){
//echo "Already Exist Exception";
try {
$exist_customer = Mage::getModel("customer/customer");
$exist_customer->setWebsiteId($websiteId);
$exist_customer->setCurrentStore($store);
$exist_customer->loadByEmail($email);
$res["id"] = $exist_customer->getId();
$res["status"] = 1;
}
catch(Exception $ex) {
$res["id"] = -1;
$res["status"] = 0;
}
}
return $res;
I have two connected tables - days and user_days:
DAYS:
USER_DAYS:
How I need to check if there is today (unix_date) record in user_days with user_id, and if yes then I need to get day_id after that to get data from table DAYS with day_id as ID...
I write:
public function getDay($user_id) {
$stmt = $this->conn->prepare("SELECT d.id, d.day, d.status, d.created_at, d.dayDate from days d, user_days ud WHERE d.id = ? AND ud.dayDate = d.dayDate AND ud.user_id = ?");
$t=time();
$dayDate = date("Y-m-d",$t);
$stmt->bind_param("si", $dayDate, $user_id);
if ($stmt->execute()) {
$res = array();
$stmt->bind_result($id, $day, $status, $created_at, $dayDate);
// TODO
// $task = $stmt->get_result()->fetch_assoc();
$stmt->fetch();
$res["id"] = $id;
$res["task"] = $task;
$res["status"] = $status;
$res["created_at"] = $created_at;
$res["dayDate"] = $dayDate;
$stmt->close();
return $res;
} else {
return NULL;
}
}
on other side as index.php I have less important code:
$app->get('/days', 'authenticate', function() {
global $user_id;
$response = array();
$db = new DbHandler();
// fetch task
$result = $db->getDay($user_id);
if ($result != NULL) {
$response["error"] = false;
$response["id"] = $result["id"];
$response["day"] = $result["day"];
$response["status"] = $result["status"];
$response["createdAt"] = $result["created_at"];
$response["dayDate"] = $result["dayDate"];
echoRespnse(200, $response);
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
I just get this output which is not correct:
Object {error: false, id: 0, day: null, status: 0, createdAt: null}
What is wrong with my QUERY, I think that QUERY is problem but I can solve it by hours...
In getday(), I think you should replace $res["task"] = $task; with $res["day"]=$day.