I have written a web service for order creation as below
<?php
#ini_set('display_errors', 'on');
define('_PS_DEBUG_SQL_', true);
require_once('db.php');
require_once('PSWebServiceLibrary.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$customerId = $_POST['customerid'];
$address = $_POST['address'];
$phoneno = $_POST['phoneno'];
$city = $_POST['city'];
$postcode = $_POST['postcode'];
$totalprice = $_POST['totalprice'];
$orders = $_POST['orders'];
$firstname = $_POST['firstname'] ;
$lastname = $_POST['lastname'] ;
$paymethod = "cod"; // cod or payu// cod or payu
$curdate=date('Y-m-d H:i:s');
if($paymethod == "payu") {
$orderModule = "citruspayu" ;
$orderPayment = "PayUmoney " ;
} else if($paymethod =="cod") {
$orderModule = "ps_cashondelivery" ;
$orderPayment = "Cash on delivery (cod)" ;
}
$curdate=date('Y-m-d H:i:s');
$orders = str_replace("\\", "",$orders);
$orders = json_decode($orders, true) ;
$ocnt=sizeof($orders);
//print_r($ocnt);
// need to check with product id and qunatity - ps_stock_available
// for ($i = 0 ; $i < $ocnt ; $i++) {
// $proid= $orders[$i]['product_id'];
// $quan=$orders[$i]['total_qty'];
// }
$result = array() ;
// print_r($result);
try
{
$sql=mysqli_query($con,"select * from `ps_customer` WHERE id_customer='".$customerId."'");
$cnt=mysqli_affected_rows($con);
if($cnt!=0) { //to place order
$row=mysqli_fetch_assoc($sql);
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/addresses?ws_key='.PS_WS_AUTH_KEY.'&schema=synopsis'));
$resources = $xml->children()->children();
$resources->id_country = 110; //India
$resources->id_state = 348; //Tamil Nadu
$resources->id_customer = $customerId;
$resources->alias = "My address";
$resources->lastname = $lastname ; //$row['lastname'];// last name is required
$resources->firstname = $firstname;
$resources->address1 = $address;
$resources->postcode = $postcode;
$resources->city = $city;
$resources->phone_mobile = $phoneno;
$resources->active = 1;
$resources->date_add = date('Y-m-d H:i:s');
$resources->date_upd = date('Y-m-d H:i:s');
$sql = mysqli_query($con,"select * from ps_address where id_customer=$customerId and firstname='".$firstname."' and lastname='".$lastname."' and address1='".$address."' and city='".$city."' and postcode='".$postcode."' and (phone_mobile= $phoneno or phone=$phoneno)");
//$sqll= "select * from ps_address where id_customer=$customerId and firstname='".$firstname."' and lastname='".$lastname."' and address1='".$address."' and city='".$city."' and postcode='".$postcode."' and (phone_mobile= $phoneno or phone=$phoneno)";
// echo $sqll;
$cnt=mysqli_num_rows($sql);
// echo "addrs count....".($cnt);
if($cnt == 0) {
$opt = array('resource' => 'addresses?ws_key='.PS_WS_AUTH_KEY.'&schema=synopsis');
// echo "111";
$opt['postXml'] = $xml->asXML();// echo $opt['postXml'];
// echo "222";
$xml = $webService->add($opt);
// echo "333";
$addressid = $xml->address->id;
// echo "string".$addressid;
}
else {
$address=mysqli_fetch_assoc($sql) ;
$addressid = $address['id_address'] ;
//echo "address id---".$addressid ;
}
//echo "now";
//exit();
if($addressid) { // if addressid exists
// to insert cart details
$cxml = $webService->get(array('url' => PS_SHOP_PATH.'/api/carts?ws_key='.PS_WS_AUTH_KEY.'&schema=synopsis'));
$cresources = $cxml->children()->children();
$cresources->id_carrier = 4;
$cresources->id_shop_group = 1;
$cresources->id_shop = 1;
$cresources->delivery_option = 'a:1:{i:'.$addressid.';s:2:"4,";}';
$cresources->id_customer = $customerId;
$cresources->id_lang = 2;
$cresources->id_address_delivery =$addressid;
$cresources->id_address_invoice = $addressid;
$cresources->id_currency = 1;
$cresources->id_guest = 1;
$cresources->date_add = date('Y-m-d H:i:s');
$cresources->date_upd = date('Y-m-d H:i:s');
$opt = array('resource' => 'carts?ws_key='.PS_WS_AUTH_KEY.'&schema=synopsis');
$opt['postXml'] = $cxml->asXML();
$cxml = $webService->add($opt);
$cartid = $cxml->cart->id;
echo "cart id===".$cartid ;
if($cxml) {
/*insert cart product*/
$delqur = mysqli_query($con,"DELETE FROM ps_cart_product WHERE id_cart = $cartid;");
for ($i = 0 ; $i < $ocnt ; $i++) {
$proid= $orders[$i]['product_id'];
$quan=$orders[$i]['total_qty'];
$qur = mysqli_query($con,"INSERT INTO ps_cart_product (`id_cart`,`id_product`,`id_address_delivery`,`id_shop`,
`id_product_attribute`,`quantity`,`date_add`) VALUES('$cartid','$proid','$addressid','1','0','$quan','$curdate');");
}
/*insert cart product*/
/*to insert order details*/
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$orderxml = $webService->get(array('url' => PS_SHOP_PATH.'/api/orders?ws_key='.PS_WS_AUTH_KEY.'&schema=synopsis'));
$orderxml->order->id_address_delivery = $addressid;
$orderxml->order->id_address_invoice = $addressid;
$orderxml->order->id_cart = $cartid;
$orderxml->order->id_currency = 1;
$orderxml->order->id_lang = 2;
$orderxml->order->id_customer = $customerId;
$orderxml->order->id_carrier = 4; // Check your id_carrier
$orderxml->order->current_state = 3;
$orderxml->order->module = $orderModule ;
//'citruspayu' ; //'ps_cashondelivery';
$orderxml->order->valid = 0;
$orderxml->order->id_shop_group = 1;
$xml->order->id_shop = 1;
$orderxml->order->payment = $orderPayment ;
//"PayUmoney" ; //'Cash on delivery (COD)';
$orderxml->order->total_discounts = 0;
$orderxml->order->total_discounts_tax_incl =0;
$orderxml->order->total_discounts_tax_excl =0;
$orderxml->order->total_paid = $totalprice;
$orderxml->order->total_paid_tax_incl = $totalprice;
$orderxml->order->total_paid_tax_excl = $totalprice;
$orderxml->order->total_paid_real = $totalprice;
$orderxml->order->total_products = 2 ;
$orderxml->order->total_products_wt = 200 ;
$orderxml->order->total_shipping = 0;
$orderxml->order->total_shipping_tax_incl = 0;
$orderxml->order->total_shipping_tax_excl = 0;
$orderxml->order->conversion_rate = 1;
// $orderxml->order->from_device="app" ;
$orderxml->order->secure_key = md5(uniqid(rand(), true));;
$opt = array('resource' => 'orders?sendemail=1');
$orderxml = $orderxml->asXML();
$opt['postXml'] = $orderxml ; //echo $opt['postXml'];
$orderxml = $webService->add($opt);
$orderid=$orderxml->order->id;
if($orderxml) {
$findSecLastInvoice=mysqli_query($con,"SELECT * FROM `ps_order_invoice` ORDER BY `delivery_number` DESC LIMIT 1");
$icnt=mysqli_affected_rows($con);
if($icnt!=0) {
$inrow=mysqli_fetch_assoc($findSecLastInvoice);
$dnumber =$inrow['delivery_number'] + 1;
} else {
$dnumber =1;
}
$findOrderid=mysqli_query($con,"SELECT * FROM `ps_orders` WHERE id_cart='$cartid'");
$orderrow=mysqli_fetch_assoc($findOrderid);
$update_orderinvoice = mysqli_query($con, "UPDATE ps_order_invoice SET delivery_number='$dnumber',delivery_date='$curdate' WHERE id_order='".$orderrow['id_order']."'") ;
if($update_orderinvoice) {
$update_order = mysqli_query($con, "UPDATE ps_orders SET delivery_number='$dnumber',delivery_date='$curdate' WHERE id_order='".$orderrow['id_order']."'") ;
$update_orderhistory = mysqli_query($con, "UPDATE ps_order_history WHERE id_order='".$orderrow['id_order']."'") ;
$result['status']= "Success";
$result['orderid'] = strval($orderid) ;
}
} else {
$result['status']= "Error";
} //$oxml
} //$cxml
// to insert cart details
} //$address id
}
else { //not exists
$result['status']="Account Not Found";
}
// header('Content-type: application/json');
echo json_encode($result);
mysqli_close($con);
}
catch (PrestaShopWebserviceException $e)
{
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$e->getMessage();
}
}//post
else {
echo "No Post Parameters" ;
}
//}
?>
While running in postman I get a success message. but when I see app log am getting an error as HTTP XML response is not parsable and LibXMLError::__set_state error...somebody pls help. I have also trimmed it but no use.1
I'm using PSWebServiceLibrary.php for Prestashop and in the add function, this is the code which sends the XML request for parsing.
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;
}
}
In my code am trying to verify if query is true before outputing result i have tried:
require("init.php");
if(empty($_GET["book"]) && empty($_GET["url"])) {
$_SESSION["msg"] = 'Request not valid';
header("location:obinnaa.php");
}
if(isset($_GET["book"]) && isset($_GET["url"])) {
$book = $_GET['book'];
$url = $_GET['url'];
$drs = urldecode("$url");
$txt = encrypt_decrypt('decrypt', $book);
if(!preg_match('/(proc)/i', $url)) {
$_SESSION["msg"] = 'ticket printer has faild';
header("location:obinnaa.php");
exit();
} else {
$ql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
if($count < 1) {
$_SESSION["msg"] = 'Transation has oready been made by a customer please check and try again';
header("location:obinnaa.php");
exit();
}
while($riow = mysqli_fetch_assoc($ql)) {
$id = $riow["id"];
$tqty = $riow["quantity"];
for($b = 0; $b < $tqty; $b++) {
$run = rand_string(5);
$dua .= $run;
}
}
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$split = $dua;
$show_plit = str_split($split, 5);
$b = 0;
while($row = mysqli_fetch_assoc($sql)) {
$id = $row["id"];
$qty = $row["quantity"];
$oldB = $b;
$am = " ";
for(; $b < $oldB + $qty; $b++) {
$am .= "$show_plit[$b]";
$lek = mysqli_query($conn, "UPDATE books SET ticket='$am' WHERE id=$id");
}
if($lek) {
$adr = urlencode($adr = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$ty = encrypt_decrypt("encrypt", $txt);
$vars = array(
"book" => $ty,
"url" => $adr
);
$querystring = http_build_query($vars);
$adr = "viewbuy.php?" . $querystring;
header("location: $adr");
} else {
$_SESSION["msg"] = 'Transation failed unknow error';
header("location:obinnaa.php");
}
}
}
}
but i get to
$_SESSION["msg"]='Transation has oready been made by a customer please check and try again
even when the query is right what are mine doing wrong.
Check your return variable name from the query. You have $ql when it should be $sql.
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
A good IDE would flag this. NetBeans is a good free one.
Public Service Announcement:
NEVER build SQL queries straight from a URL parameter. Always sanitize your inputs and (better yet) use parameterized queries for your SQL calls. You can Google these topics for more info.
I am working on a site where people can get a bitcoin adres. When I do the GET request to the file, it gives a response of HTTP error 500. But I can't find any wrong things. Her is my script:
<?php
ob_start();
session_start();
error_reporting(0);
include("../includes/config.php");
$db = new mysqli($CONF['host'], $CONF['user'], $CONF['pass'], $CONF['name']);
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
$db->set_charset("utf8");
$settingsQuery = $db->query("SELECT * FROM btc_settings ORDER BY id DESC LIMIT 1");
$settings = $settingsQuery->fetch_assoc();
include("../includes/block_io.php");
include("../includes/functions.php");
//include(getLanguage($settings['url'],null,2));
if(checkSession()) {
$type = protect($_GET['type']);
if($type == "receive") {
} elseif($type == "new_address") {
$nums = $db->query("SELECT * FROM btc_users_addresses WHERE uid='".$_SESSION['btc_uid']."'");
if($nums->num_rows > $settings['max_addresses_per_account']) {
$data['status'] = 'error';
$data['msg'] = error("You've reached the limit of wallet addresses. Max: $settings[max_addresses_per_account]");
} else {
$label = protect($_POST['label']);
if(!empty($label) && !isValidUsername($label)) { $data['status'] = 'error'; $data['msg'] = error("Please enter valid label. Use only characters and symbols - and _."); }
else {
if(empty($label)) { $label = randomHash(7); }
$username = idinfo($_SESSION['btc_uid'],"username");
$generate_address = btc_generate_address($username,$label);
if($generate_address) {
$data['status'] = 'success';
$data['msg'] = success("Your new address is <b>" . $generate_address . "</b>.");
} else {
$data['status'] = 'error';
$data['msg'] = error("Error with creating address. Please try again.");
}
}
}
echo json_encode($data);
} elseif($type == "send_bitcoins") {
$address = protect($_GET['from_address']);
$to_address = protect($_POST['to_address']);
$amount = protect($_POST['amount']);
$secret_pin = protect($_POST['secret_pin']);
$secret_pin = md5($secret_pin);
$check = $db->query("SELECT * FROM btc_users_addresses WHERE uid='".$_SESSION[btc_uid]."' and address='$address'");
if($check->num_rows==0) {
$data['status'] = 'error';
$data['msg'] = error("This wallet address is not yours!");
} elseif(empty($address) or empty($to_address) or empty($amount)) {
$data['status'] = 'error';
$data['msg'] = error("All fields are required.");
} elseif(!is_numeric($amount)) {
$data['status'] = 'error';
$data['msg'] = error("Please enter Bitcoin amount with numbers. Format: 0.000000");
} elseif(idinfo($_SESSION['btc_uid'],"secret_pin") && idinfo($_SESSION['btc_uid'],"secret_pin") !== $secret_pin) {
$data['status'] = 'error';
$data['msg'] = error("Wrong Secret PIN!");
} else {
$row = $check->fetch_assoc();
$total = $row['available_balance'];
$total = $total - 0.0008;
$total = $total - $settings['withdrawal_comission'];
if($total < 0) { $total = '0.0000'; }
if($amount > $total) {
$data['status'] = 'error';
$data['msg'] = error("Total available minus fees <b>" . $total . "</b> BTC.");
} else {
$newamount = $row['available_balance']-$amount;
$newamount = $newamount - 0.0008 - $settings['withdrawal_comission'];
$license_query = $db->query("SELECT * FROM btc_blockio_licenses WHERE id='".$row[lid]."' ORDER BY id");
$license = $license_query->fetch_assoc();
$apiKey = $license['license'];
$pin = $license['secret_pin'];
$version = 2; // the API version
$block_io = new BlockIo($apiKey, $pin, $version);
$withdrawal = $block_io->withdraw_from_addresses(array('amounts' => $amount, 'from_addresses' => $address, 'to_addresses' => $to_address));
$withdrawal = $block_io->withdraw_from_addresses(array('amounts' => $settings[withdrawal_comission], 'from_addresses' => $address, 'to_addresses' => $license[address]));
$data['status'] = 'success';
$data['msg'] = success("You sent <b>" . $amount . "</b> BTC to <b>" . $to_address . "</b> successfully.");
$data['btc_total'] = $newamount;
}
}
echo json_encode($data);
} elseif($type == "receive_to_address") {
} elseif($type == "archive_address") {
$address_id = protect($_GET['address_id']);
$query = $db->query("SELECT * FROM btc_users_addresses WHERE uid='".$_SESSION[btc_uid]."' and id='".$address_id."'");
if($query->num_rows>0) {
$row = $query->fetch_assoc();
if($row['archived'] == "1") {
echo 'Your wallet address <b>'.$row[address].'</b> is already archived.';
} else {
$update = $db->query("UPDATE btc_users_addresses SET archived='1' WHERE id='".$row[id]."'");
echo 'Your wallet address <b>'.$row[address].'</b> was archived.';
}
} else {
echo 'This wallet address is not yours!';
}
} elseif($type == "unarchive_address") {
$address_id = protect($_GET['address_id']);
$query = $db->query("SELECT * FROM btc_users_addresses WHERE uid='".$_SESSION[btc_uid]."' and id='".$address_id."'");
if($query->num_rows>0) {
$row = $query->fetch_assoc();
if($row['archived'] == "0") {
echo 'Your wallet address <b>'.$row[address].'</b> is already unarchived.';
} else {
$update = $db->query("UPDATE btc_users_addresses SET archived='0' WHERE id='".$row[id]."'");
echo 'Your wallet address <b>'.$row[address].'</b> was unarchived.';
}
} else {
echo 'This wallet address is not yours!';
}
} else { }
}
?>
Thank you for helping me out! It must to give the address back...
I am trying to pass a strret address from my application to my PHP server.
when i print the address in the Log.d i got:
העמק 57 גבעת אלה
but the server response is:
$place = $_POST["address"];
$output["addressEditText"] = $place;
and this is what i got from the server:
???? 57 ???? ???
i need that the server will support also hebrew alphabet.
just for notice this response is not from the DB i just copy and past the value of the parameter into the output response.
this is my page code:
<?php
/**
* Created by PhpStorm.
* User: matant
* Date: 9/17/2015
* Time: 2:56 PM
*/
include 'response_process.php';
include 'gcm.php';
require_once 'DBFunctions.php';
class CreateEvent implements ResponseProcess {
public function dataProcess($dblink)
{
$output = array();
$dbF = new DBFunctions($dblink);
$sport = $_POST["sport_type"];
$date = date("Y-m-d",strtotime(str_replace('/','-',$_POST["date"])));
$s_time =$date." ".$_POST["s_time"];
$e_time = $date." ".$_POST["e_time"];
$s_time =date("Y-m-d H:i:s",strtotime($s_time));
$e_time = date("Y-m-d H:i:s",strtotime($e_time));
$lon = $_POST["lon"];
$lat = $_POST["lat"];
$event_type = $_POST["event_type"];
$max_p = $_POST["max_participants"];
$sched = $_POST["scheduled"];
$gen = $_POST["gender"];
$min_age = $_POST["minAge"];
$manager = $_POST["manager"];
$mng_name = $_POST["manager_name"];
$place = $_POST["address"];
$output["addressEditText"] = $place;
$mode = $_POST["mode"];
if($sched == "true"){
$exp_val = "";
$type = "";
$repeat = $_POST["repeat"];
$duration = $_POST["duration"];
$expiration_tag = $_POST["sched_tag"];
switch($expiration_tag){
case "unlimited":{
$exp_val = "unlimited";
$type = $exp_val;
break;
}
case "Year":{
$exp_val = date("Y-m-d",strtotime($_POST["value"]));
$type = "date";
break;
}
case "events_number":
$exp_val = $_POST["value"];
$type = "counter";
break;
case "by_date":
$exp_val = date("Y-m-d",strtotime($_POST["value"]));
$type = "date";
break;
}
$output["repeat"] = $repeat;
$output["duration"] = $duration;
$output["exp_val"] = $exp_val;
$output["type"] = $type;
}
if($mode == "edit"){
$event_id = $_POST["event_id"];
$invited_users_size = 0;
if(isset($_POST["invitedUsers"])){
$participants = $_POST["invitedUsers"];
$json_uesr_ids = json_decode($participants);
$invited_users_size = count($json_uesr_ids);
}
if(isset($_POST["invitedUsers"])){
$result_q = $dbF -> DeleteEventFromAttending($event_id);
if(!$result_q)
{
$output["flag"]= "delete failed";
$output["msg"] = $result_q;
return json_encode($output);
}else {
$participants = $_POST["invitedUsers"];
$json_uesr_ids = json_decode($participants);
$output["json_users"] = $json_uesr_ids;
$get_users_reg_ids = $dbF->getUserSByIds($json_uesr_ids, count($json_uesr_ids));
$reg_ids = array();
$i = 0;
while ($row_user = mysqli_fetch_assoc($get_users_reg_ids)) {
$reg_ids[$i] = $row_user["gcm_id"];
$i++;
}
$output["ids"] = $reg_ids;
$output["size"] = count($json_uesr_ids);
$result_q = $dbF->InsertIntoAttendingUpdatedUsers($json_uesr_ids, $event_id, count($json_uesr_ids),"awaiting reply");
$output["insert_res"] = $result_q;
if (!$result_q) {
$output["flag"] = "update_insert failed";
$output["msg"] = $result_q;
return json_encode($output);
} else {
$output["flag"] = "update_success";
$output["msg"] = $result_q;
}
//send notification on update to users
$gcm = new GCM();
$data = array();
$message = "The event " . $sport . " in " . $place . " in " . $date . " updated,Please click on Join in order to confirm registration.";
$data['message'] = $message;
$data['date'] = $date;
$data['private'] = $event_type;
$data['start_time'] = date("H:i", strtotime($s_time));
$data['end_time'] = date("H:i", strtotime($e_time));
$data['inviter'] = $mng_name;
$data['event_id'] = $event_id;
$data['location'] = $place;
$gcm_res = $gcm->send_notification($reg_ids, $data);
$output["gcm_res"] = $gcm_res;
//send notification on update to users
}
}
$result_q = $dbF ->checkIfEventIsExistBeforeUpdate($lon,$lat,$date,$s_time,$e_time,$event_id);
if(!$result_q)
{
$output["flag"]= "select failed";
$output["msg"] = $result_q;
return json_encode($output);
}
else {
$no_of_rows_check_event = mysqli_num_rows($result_q);
if ($no_of_rows_check_event > 0) {
$output["flag"] = "failed";
$output["msg"] = "Place is already occupied in this time";
}else{
$result_q = $dbF -> UpdateEvent($event_id,$sport,$s_time,$e_time,$place,$lon,$lat,$event_type,$gen,$min_age,$max_p,'1',$invited_users_size,$sched,$output["repeat"],$output["duration"],$output["type"],$output["exp_val"]);
$output["res"] = $result_q;
$output["sched"] = $sched;
if($sched == "true")
{
$output["sched_res"] = "true";
}
else{
$output["sched_res"] = "false";
}
$affected_row = mysqli_affected_rows($dblink);
if(!$result_q)
{
$output["flag"]= "update_failed";
$output["query_res"] = $result_q;
$output["msg"] = "failed to update event";
$output["affected row"] = $affected_row;
}
else{
$output["flag"]= "update_success";
$output["query_res"] = $result_q;
$output["msg"] = "success to update event";
$output["affected row"] = $affected_row;
}
}
}
}
else{
$result_q = $dbF ->checkIfEventIsExist($lon,$lat,$date,$s_time,$e_time);
$output["query"] = $result_q;
if(!$result_q)
{
$output["flag"]= "select failed";
$output["msg"] = $result_q;
return json_encode($output);
}
else{
$no_of_rows_check_event = mysqli_num_rows($result_q);
$output["no_of_rows"] = $no_of_rows_check_event;
if($no_of_rows_check_event > 0)
{
$output["flag"] = "failed";
$output["msg"] = "Place is already occupied in this time";
}else{
$output["flag"] = "success";
$output["msg"] = "insert event";
$num_of_invited_users = 0;
if(isset($_POST["jsoninvited"])){
$json = $_POST["jsoninvited"];
$json = json_decode($json);
$num_of_invited_users = (count($json));
$output["size_invited"] = count($json);
}
$result = $dbF -> InsertNewEvent($manager,$sport,$s_time,$e_time,$place,$lon,$lat,$event_type,$gen,$min_age,$max_p,$num_of_invited_users,$sched,$output["repeat"],$output["duration"],$output["type"],$output["exp_val"]);
if (!$result) {
$output["flag"] = "failed to create event";
// return (json_encode($output));
}
else{
if(isset($_POST["jsoninvited"])){
$event_s_res = $dbF ->getEventIdByDateAndTime($date,$s_time,$e_time);
$output["my_squery"] =$event_s_res;
if(!$event_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$row = mysqli_fetch_assoc($event_s_res);
$no_of_rows = mysqli_num_rows($event_s_res);
if($no_of_rows > 1 || $no_of_rows == 0)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$event_id = $row["event_id"];
$json = $_POST["jsoninvited"];
$json = json_decode($json);
$output["size_invited"] = count($json);
$size_of_param = (count($json));
$event_user_s_res = $dbF -> getUserIdAndRegId($json,$size_of_param);
if(!$event_user_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "user id not found";
}
$result = $dbF->insertIntoAttendingTable($event_user_s_res, $event_id, $size_of_param);
$insert_query_res = $result["res"];
$output["query"] = $result["query"];
$registration_ids = $result["reg_ids"];
if(!$insert_query_res)
{
$output["flag"] = "failed";
$output["msg"] = "failed to insert to attending table";
}
else{
$output["registred_ids"] = $registration_ids;
$output["msg"] = "success to insert into attending";
$gcm = new GCM();
$data = array();
$message = "Would like to invite you to play ".$sport.", Please click on Join in order to add you into the event.";
$data['message'] = $message;
$data['date'] = $date;
$data['start_time'] = date("H:i",strtotime($s_time));
$data['end_time'] = date("H:i",strtotime($e_time));
$data['inviter'] = $mng_name;
$data['private'] = $event_type;
$data['event_id'] = $event_id;
$data['location'] = $place;
$output["gcm_message"]=$data;
$gcm_res = $gcm->send_notification($registration_ids,$data);
$output["gcm_res"] = $gcm_res;
} //els of $insert_query_res
} //else of $no_of_rows > 1 || $no_of_rows == 0
} // else of $event_s_res
} //if isset($_POST["invitedUsers"]
} // if $result
}
}
}//get inside creating event mode.
return json_encode($output);
}
}
this is my client side:
public void sendDataToDBController() {
BasicNameValuePair mode_req;
LatLng lonlat = locationTool.getLocationFromAddress(addressEditText.getText().toString());
if(lonlat == null)
{
Log.d("location is:","location not found");
sv.scrollTo(0, 0);
addressEditText.setError("Location was not found!");
return;
}
Log.d("found location",lonlat.latitude+""+lonlat.longitude);
BasicNameValuePair tagreq = new BasicNameValuePair(Constants.TAG_REQUEST,"create_event");
Log.d("event mode",mode);
if(mode.equals(Constants.MODE_CREATE))
{
Log.d("event mode","create");
mode_req = new BasicNameValuePair(Constants.TAG_MODE,Constants.MODE_CREATE);
}
else {
Log.d("event mode","update");
mode_req = new BasicNameValuePair(Constants.TAG_MODE, Constants.MODE_UPDATE);
}
Log.d("addressEditText",addressEditText.getText().toString());
BasicNameValuePair address = new BasicNameValuePair("address",addressEditText.getText().toString());
BasicNameValuePair sport = new BasicNameValuePair("sport_type",sportSpinner.getSelectedItem().toString());
Log.d("sport_type",sportSpinner.getSelectedItem().toString());
BasicNameValuePair date = new BasicNameValuePair("date",btnStartdate.getText().toString());
BasicNameValuePair startTime = new BasicNameValuePair("s_time",btnstartTime.getText().toString());
BasicNameValuePair endTime = new BasicNameValuePair("e_time",btnendTime.getText().toString());
BasicNameValuePair longtitude = new BasicNameValuePair(Constants.TAG_LONG,String.valueOf(lonlat.longitude));
BasicNameValuePair latitude = new BasicNameValuePair(Constants.TAG_LAT,String.valueOf(lonlat.latitude));
BasicNameValuePair event_type = new BasicNameValuePair("event_type",String.valueOf(privateEventCbox.isChecked()));
BasicNameValuePair gender = new BasicNameValuePair(Constants.TAG_GEN,String.valueOf(genderSpinner.getSelectedItem().toString()));
BasicNameValuePair min_age = new BasicNameValuePair("minAge",String.valueOf(minAgeEditText.getText()));
BasicNameValuePair participants = new BasicNameValuePair("max_participants",maxParticipantsEdittext.getText().toString());
BasicNameValuePair scheduled = new BasicNameValuePair("scheduled",String.valueOf(reccuringEventCbox.isChecked()));
BasicNameValuePair mob_manager = new BasicNameValuePair("manager",sm.getUserDetails().get(Constants.TAG_USERID));
BasicNameValuePair manager_name = new BasicNameValuePair("manager_name",sm.getUserDetails().get(Constants.TAG_NAME));
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
if(mode.equals(Constants.MODE_UPDATE)){
BasicNameValuePair eventId = new BasicNameValuePair("event_id",event_id);
nameValuePairList.add(eventId);
}
if(invitedUsers != null)
{
if(invitedUsers.size() > 0)
{
String[] users = new String[invitedUsers.size()];
JSONArray invited = new JSONArray();
for(int i=0 ; i < invitedUsers.size(); i++)
{
if(mode.equals(Constants.MODE_CREATE))
users[i]= invitedUsers.get(i).getMobile();
else
users[i]= invitedUsers.get(i).getId();
invited.put(users[i]);
}
String json = invited.toString();
Log.d("string array", Arrays.toString(users));
BasicNameValuePair invitedusers = new BasicNameValuePair("invitedUsers",Arrays.toString(users));
BasicNameValuePair jsonInvited = new BasicNameValuePair("jsoninvited",json);
nameValuePairList.add(invitedusers);
nameValuePairList.add(jsonInvited);
}
}
if(sched_res != null && reccuringEventCbox.isChecked() == true){
String repeatval ="";
String duration ="";
String tag = "";
String val = "";
BasicNameValuePair sched_val = null;
try {
repeatval = sched_res.getString("repeat");
duration = sched_res.getString("duration");
JSONArray jsonarr = new JSONArray(sched_res.getString("radio_group"));
tag = jsonarr.getJSONObject(0).getString(Constants.TAG_REQUEST);
sched_val = new BasicNameValuePair("value",jsonarr.getJSONObject(0).getString("val"));
} catch (JSONException e) {
e.printStackTrace();
}
BasicNameValuePair sched_repeat = new BasicNameValuePair("repeat",repeatval);
BasicNameValuePair sched_duration = new BasicNameValuePair("duration",duration);
BasicNameValuePair sched_tag = new BasicNameValuePair("sched_tag",tag);
nameValuePairList.add(sched_repeat);
nameValuePairList.add(sched_duration);
nameValuePairList.add(sched_tag);
if(sched_val != null)
nameValuePairList.add(sched_val);
}
nameValuePairList.add(manager_name);
nameValuePairList.add(mob_manager);
nameValuePairList.add(tagreq);
nameValuePairList.add(mode_req);
nameValuePairList.add(sport);
nameValuePairList.add(date);
nameValuePairList.add(address);
nameValuePairList.add(startTime);
nameValuePairList.add(endTime);
nameValuePairList.add(min_age);
nameValuePairList.add(longtitude);
nameValuePairList.add(latitude);
nameValuePairList.add(event_type);
nameValuePairList.add(participants);
nameValuePairList.add(scheduled);
nameValuePairList.add(gender);
dbController = new DBcontroller(getActivity().getApplicationContext(),this);
dbController.execute(nameValuePairList);
}
after searching for a while i solved this issue by:
add this code in my server side:
if(!mysqli_set_charset($dblink, 'utf8')) {
echo 'the connection is not in utf8';
exit();
}
i try to get results from my server. my application sending an array with users info and should insert that into the DB.
i get the following result:
{"flag":"failed","msg":"insert event","event id":"89","invitedusers":"[0508690186, 0508690187]","size_invited":1,"user_query":"SELECT id From users WHERE "}
and i would like to know how can i read the values in PHP under "invitedusers":"[0508690186, 0508690187]"
this is my php code:
<?php
/**
* Created by PhpStorm.
* User: matant
* Date: 9/17/2015
* Time: 2:56 PM
*/
include 'response_process.php';
class CreateEvent implements ResponseProcess {
public function dataProcess($dblink)
{
$output = array();
$sport = $_POST["sport_type"];
$date = date("Y-m-d",strtotime(str_replace('/','-',$_POST["date"])));
$s_time =$_POST["s_time"];
$e_time = $_POST["e_time"];
$lon = $_POST["lon"];
$lat = $_POST["lat"];
$event_type = $_POST["event_type"];
$max_p = $_POST["max_participants"];
$sched = $_POST["scheduled"];
$gen = $_POST["gender"];
$min_age = $_POST["minAge"];
$query = "SELECT * FROM event WHERE (event.longtitude = '$lon' AND event.latitude = '$lat')
AND event.event_date = '$date' And ((event.start_time BETWEEN '$s_time' AND '$e_time') OR (event.end_time BETWEEN '$s_time' AND '$e_time'))";
//AND (event.start_time = '$s_time' AND event.end_time = '$e_time')
//check time and place of the event
$result_q = mysqli_query($dblink,$query) or die (mysqli_error($dblink));
if(!$result_q)
{
$output["flag"]= "select failed";
$output["msg"] = $result_q;
return json_encode($output);
}
//case date and time are available
else {
$no_of_rows = mysqli_num_rows($result_q);
if ($no_of_rows < 1) {
$output["flag"] = "success";
$output["msg"] = "insert event";
$result = mysqli_query($dblink, "INSERT into event(kind_of_sport,event_date,start_time,end_time,longtitude,latitude,private,gender,min_age,max_participants,scheduled,event_status)
VALUES ('$sport','$date','$s_time','$e_time','$lon','$lat','$event_type','$gen','$min_age','$max_p','$sched','1')") or die (mysqli_error($dblink));
if (!$result) {
$output["flag"] = "failed to create event";
// return (json_encode($output));
}
if(isset($_POST["invitedUsers"])){
$query_id = "SELECT id From event WHERE event.event_date = '$date' and event.start_time = '$s_time' and event.end_time = '$e_time'";
$event_s_res = mysqli_query($dblink,$query_id) or die (mysqli_error($dblink));
if(!$event_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$row = mysqli_fetch_assoc($event_s_res);
$output["event id"]=$row["id"];
$json = json_decode($_POST["invitedUsers"]);
$invited_users = str_replace("\\","",$json);
$output["invitedusers"] = $_POST["invitedUsers"] ;
$output["size_invited"] = count($_POST["invitedUsers"]);
$query_users = "SELECT id From users WHERE ";
$i=0;
foreach($invited_users as $user) {
if ($i < (count($invited_users) - 1))
// add a space at end of this string
$query_users .= "users.mobile = '".$user[$i]."' or ";
else {
// and this one too
$query_users .= "users.mobile = '".$user[$i]."' ";
$output["users"][] = $user['mobile'];
}
$i++;
$output["index"]=$i;
}
$output["user_query"]= $query_users;
/* $event_user_s_res = mysqli_query($dblink,$query_users) or die (mysqli_error($dblink));
if(!$event_user_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "user id not found";
}*/
}
$output["flag"] = "failed";
}
}
else {
$output["flag"] = "failed";
$output["msg"] = "Place is already occupied in this time";
}
}
return json_encode($output);
}
}
i resolve this issue by passing a JSON object from the application and using
json_decode method which convert it back.