Sync phonebook using php - php

I am working on web-service to sync contacts using yii2 framework. where i am having whole phone-book (in json array) from mobile end and i have to check which phone numbers are there in my database.
Request params would be something like this
{
"user_id": "4",
"user_details": [{
"first_name": "A",
"last_name": "A"
}, {
"first_name": "B",
"last_name": "B"
,
"mobile_number": ["(888) 888-888", "(777) 777-777"]
}, {
"first_name": "C",
"last_name": "C",
"mobile_number": ["+918000584123", "(666) 666-6666", "(555) 555-5555", "(444) 444-4444"]
}]
}
To achieve the functionality i have done following code.
public function actionSyncPhoneBook()
{
$amResponse = $amResponseData = [];
$snUserId = $this->amData['user_id'];// Here i will get user_id
if (!empty($this->omUser))
{
$userDetails = $this->amData['user_details'];//Here i will get array of user_details
$amAppContacts =[];
$amNonAppContacts = [];
//I have loop here of user details to scan mobile number array
foreach ($userDetails as $userKeys)
{
//In case if mobile number array is not given
if(!empty($userKeys["mobile_number"]))
{
// Loop for scanning mobile numbers
foreach ($userKeys["mobile_number"] as $key => $mobileNumber)
{
//regex for matching mobile number.
$phone = preg_replace('/[^a-zA-Z0-9+]/', '', $mobileNumber);
$oModelUser = Users::find()
->where(['phone' => $phone])
->one();
//Check if conttact is exists or not using exist method
$checkContactExists = Users::find()->where(['phone' => $phone])->exists();
if($checkContactExists == 1)
{
$oModelFriends = Friends::find()->where(["from_user_id"=>$snUserId,"to_user_id"=>$oModelUser->id])->asArray()->one();
$amCheckPhoneNumber['user_id'] = !empty((string)$oModelUser->id) ? (string)$oModelUser->id : '';
$amCheckPhoneNumber['first_name'] = !empty($oModelUser->first_name) ? $oModelUser->first_name : '';
$amCheckPhoneNumber['last_name'] = !empty($oModelUser->last_name) ? $oModelUser->last_name : '';
$amCheckPhoneNumber['email'] = !empty($oModelUser->email) ? $oModelUser->email : '';
$amCheckPhoneNumber['phone'] = !empty($oModelUser->phone) ? $oModelUser->phone : '';
$amCheckPhoneNumber['status'] = !empty((string)$oModelUser->status) ? (string)$oModelUser->status : '';
$amCheckPhoneNumber['relationship_status'] = !empty($oModelUser->relationship_status) ? $oModelUser->relationship_status : '';
$amCheckPhoneNumber['mobile_verified'] = !empty((string)$oModelUser->mobile_verified) ? (string)$oModelUser->mobile_verified : '';
$amCheckPhoneNumber['email_verified'] = !empty($oModelUser->email_verified) ? $oModelUser->email_verified : '';
$amCheckPhoneNumber['latitude'] = !empty($oModelUser->latitude) ? $oModelUser->latitude : "0";
$amCheckPhoneNumber['longitude'] = !empty($oModelUser->longitude) ? $oModelUser->longitude : "0";
if($oModelFriends["is_friend"] == 1)
{
$amCheckPhoneNumber['is_friend'] = "friends";
}
else
{
$amCheckPhoneNumber['is_friend'] = "no_friends";
}
//User Image
if(!empty($oModelUser->user_image))
{
if (filter_var($oModelUser->user_image, FILTER_VALIDATE_URL))
{
if(!empty($oModelUser->user_image))
{
$ssEventDetailsUserImage = $oModelUser->user_image;
}
else
{
$ssEventDetailsUserImage = Yii::$app->params['aws_cover_image_path'];
}
}
else
{
$ssEventDetailsUserImage =Yii::$app->params['aws_cover_image_path'];
}
}
else
{
$ssEventDetailsUserImage = Yii::$app->params['aws_cover_image_path'];
}
//Cover Image
if(!empty($oModelUser->cover_image))
{
if (filter_var($oModelUser->cover_image, FILTER_VALIDATE_URL))
{
if(!empty($oModelUser->cover_image))
{
$ssCoverImage = $oModelUser->cover_image;
}
else
{
$ssCoverImage = Yii::$app->params['aws_cover_image_path'];
}
}
else
{
$ssCoverImage =Yii::$app->params['aws_cover_image_path'];
}
}
else
{
$ssCoverImage = Yii::$app->params['aws_cover_image_path'];
}
$amCheckPhoneNumber['cover_image'] = !empty($ssCoverImage) ? $ssCoverImage : '';
$amCheckPhoneNumber['user_image'] = !empty($ssEventDetailsUserImage) ? $ssEventDetailsUserImage : '';
$amCheckPhoneNumber['app_user'] = "1";
//Final Response of users those who are using application
$amAppContacts[] = $amCheckPhoneNumber;
}
else
{
//Users who does not use application.
$otherUsers['user_id'] = !empty($userKeys['id']) ? $userKeys['id'] : '';
$otherUsers['first_name'] = !empty($userKeys['first_name']) ? $userKeys['first_name'] : '';
$otherUsers['last_name'] = !empty($userKeys['last_name']) ? $userKeys['last_name'] : '';
$otherUsers['email'] = !empty($userKeys['email']) ? $userKeys['email'] : '';
$otherUsers['phone'] = !empty($mobileNumber) ? $mobileNumber : '';
$otherUsers['status'] = !empty($userKeys['status']) ? $userKeys['status'] : '';
$otherUsers['relationship_status'] = !empty($userKeys['relationship_status']) ? $userKeys['relationship_status'] : '';
$otherUsers['user_image'] = Yii::$app->params['aws_cover_image_path'];
$otherUsers['cover_image'] = Yii::$app->params['aws_cover_image_path'];
$otherUsers['mobile_verified'] = !empty($userKeys['mobile_verified']) ? $userKeys['mobile_verified'] : '';
$otherUsers['email_verified'] = !empty($userKeys['email_verified']) ? $userKeys['email_verified'] : '';
$otherUsers['latitude'] = !empty($userKeys["latitude"]) ? $userKeys["latitude"] : "0";
$otherUsers['longitude'] = !empty($userKeys["longitude"]) ? $userKeys["longitude"] : "0";
$otherUsers['is_friend'] = "";
$otherUsers['app_user'] = "0";
//Final Response of users those who are not using app.
$amNonAppContacts[] = $otherUsers;
}
}
}
}
//Merging the app users and non-app users together.
$amResponseData = array_merge($amAppContacts,$amNonAppContacts);
$amResponse = Common:: successResponse("Sync your phonebook.",$amResponseData);
Common::encodeResponseJSON($amResponse);
}
}
From above code i am checking if mobile number is exist in the database than it will push into app users and rests will be in non-app users.
In my database mobile numbers are stored in the format of +(countryCode)(mobileNumber)
Example +918000584123
But it should also work if i don't pass +91 or any country codes.
It should work if mobile number array would be like
"mobile_number": ["(888) 888-888", "(777) 777-777"]
or it should be like
"mobile_number": ["+918000584123","+91 8000584123","8000584123", "(666) 666-6666", "(555) 555-5555", "(444) 444-4444"]
How to achieve this functionality?
Any help would be appreciated.
Thanks in advance.

dont need regex like this
$phone = preg_replace('/[^a-zA-Z0-9+]/', '', $mobileNumber);
Instead you can use
$phone = preg_replace('/[^0-9]/', '', $mobileNumber);
and change your where condition like this below. You should use LIKE condition
$oModelUser = Users::find()->where("phone LIKE'%".$phone."'")->one();
$checkContactExists = Users::find()->where("phone LIKE '%".$phone."'")->exists();

You tagged it with mysql, so I am answering from that angle.
The various phone number should be in a separate table, together with an id of the person they belong to. That way, there can be an arbitrary number of numbers for any person. I suggest 1:many, not many:many, and simply let the occasional shared phone be a dup number in the new table.
The table would have a non-unique index on number, thereby making it 'trivial' in SQL to locate the person(s) with a given number (or set of numbers, using IN).

Related

POST API Issue - Not functioning

Good afternoon,
I'm having trouble with an api POST request - it simply isn't going anywhere, it's not showing on the API log at all - I've got various get requests which work fine but this one just doesn't - I'm unsure what I am doing wrong.
public function broadband_plan(){
$common = array();
$common['main_menu'] = 'Broadband plan';
$cli_or_postcode = isset($_GET["cli_or_postcode"]) ? $_GET["cli_or_postcode"] : "";
$district_id = isset($_GET["district_id"]) ? $_GET["district_id"] : "";
$sub_premises = isset($_GET["sub_premises"]) ? $_GET["sub_premises"] : "";
$premises_name = isset($_GET["premises_name"]) ? $_GET["premises_name"] : "";
$thoroughfare_number = isset($_GET["thoroughfare_number"]) ? $_GET["thoroughfare_number"] : "";
$thoroughfare_name = isset($_GET["thoroughfare_name"]) ? $_GET["thoroughfare_name"] : "";
$locality = isset($_GET["locality"]) ? $_GET["locality"] : "";
$postcode = isset($_GET["postcode"]) ? $_GET["postcode"] : "";
$nad_key = isset($_GET["nad_key"]) ? $_GET["nad_key"] : "";
$post_town = isset($_GET["post_town"]) ? $_GET["post_town"] : "";
$county = isset($_GET["county"]) ? $_GET["county"] : "";
$district_id = isset($_GET["district_id"]) ? $_GET["district_id"] : "";
$request = array();
$request['apiUsername'] = 'XXXXXXX';
$request['apiPassword'] = 'XXXXXXX';
$request['encryption'] = 'SHA-512';
$request['platform'] = 'LIVE';
$request['method'] = 'POST';
$address = '{
"sub_premises": $sub_premises,
"premises_name": $premises_name,
"thoroughfare_number": $thoroughfare_number,
"thoroughfare_name": $thoroughfare_name,
"post_town": $post_town,
"postcode": $postcode,
"district_id": $district_id,
"nad_key": $nad_key
}';
$address = json_encode($address);
$request['url'] = "/broadband/availability" . $address;
$broadband_plan_detail = array();
if (!empty($address)) {
$broadband_plan_detail = $this->get_plan($request);
}
return view('front.broadband_plan',compact('common','broadband_plan_detail'));
}
The $address after $address = json_encode($address); will be an object, it cannot be concatenated as a string in $request['url'] = "/broadband/availability" . $address;
Please check your API URL and ensure you follow their structure, for example if the API URL accept the parameters as GET request, you can pass the parameters likes:
$request['url'] = "/broadband/availability?sub_premises=" . $sub_premises . "&premises_name=" . $premises_name...
Base on your code, the API method is POST, so you might need to prepare the parameters as an array.

array or variable loses value when entering if/else statement

here is some of the code where I declared the values for $list.
$list['first_name'] = Request::input("first_name");
$list['last_name'] = Request::input("last_name");
when I use dd($list), it shows the value like in my snipped image
but when it enters this if else statement,
if($existing_customer)
{
$customer_id = $existing_customer->customer_id;
}
else
{
dd($list);
$insert_customer["first_name"] = ($list['first_name'] == "undefined" ? "John" : ucfirst($list['first_name']));
$insert_customer["last_name"] = ($list['last_name'] == "undefined" ? "Doe" : ucfirst($list['last_name']));
}
this is the result.
here is the photo of my function, if it could help.
first
second
public function import_submit()
{
$data = Self::get_initial_settings();
/* INITIALIZE AND CAPTURE DATA */
$shop_id = $this->user_info->shop_id;
$sponsor = Tbl_mlm_slot::where("slot_no", Request::input("sponsor"))->where("shop_id", $shop_id)->value("slot_id");
$placement = Tbl_mlm_slot::where("slot_no", Request::input("placement"))->where("shop_id", $shop_id)->value("slot_id");
/* POSITIONING DATA */
$slot_sponsor = $sponsor;
$slot_placement = $placement;
$slot_position = strtolower(Request::input("position"));
/* SLOT GENERATION */
$membership_package_id = Request::input("package_number");
/* JUST ADD TO SLOT IF EXISTING CUSTOMER */
if(Request::input("date_created") == "undefined")
{
$slot_date_created = date("Y-m-d h:i");
}
else
{
$slot_date_created = date("Y-m-d", strtotime(Request::input("date_created")));
}
$existing_customer = Tbl_customer::where("shop_id", $shop_id)->where("email", Request::input("email"))->first();
$list['first_name'] = Request::input("first_name");
$list['last_name'] = Request::input("last_name");
$list['email'] = Request::input("email");
$list['slot_no'] = Request::input("slot_no");
$list['password'] = Request::input("password");
$list['birthday'] = Request::input("birthday");
$list['contact'] = Request::input("contact_number");
$list['gender'] = Request::input("gender");
dd($list); <---- first run of the function, I put one here
if($existing_customer)
{
$customer_id = $existing_customer->customer_id;
}
else
{
dd($list); <--- for the second run of the function, to check what happens to my $list
$insert_customer["shop_id"] = $shop_id;
$insert_customer["first_name"] = ($list['first_name'] == "undefined" ? "John" : ucfirst($list['first_name']));
$insert_customer["last_name"] = ($list['last_name'] == "undefined" ? "Doe" : ucfirst($list['last_name']));
$insert_customer["email"] = ($list['email'] == "undefined" ? "dummy#gmail.com" : $list['email']);
$insert_customer["ismlm"] = 1;
$insert_customer["mlm_username"] = $list['slot_no'];
$insert_customer["password"] = ($list['password'] == "undefined" ? Crypt::encrypt(randomPassword()) : Crypt::encrypt($list['password']));
$insert_customer["created_date"] = $slot_date_created;
$insert_customer["b_day"] = date("Y-m-d", strtotime($list['birthday']));
$insert_customer["birthday"] = date("Y-m-d", strtotime($list['birthday']));
$insert_customer["contact"] = $list['contact'];
$insert_customer["gender"] = strtolower($list['gender']);
$customer_id = Tbl_customer::insertGetId($insert_customer);
/* Insert Customer Address */
$address_purpose[0] = "permanent";
$address_purpose[1] = "billing";
$address_purpose[2] = "shipping";
foreach ($address_purpose as $key => $value)
{
$insert_customer_address["customer_id"] = $customer_id;
$insert_customer_address["country_id"] = 420;
$insert_customer_address["customer_state"] = "";
$insert_customer_address["customer_city"] = "";
$insert_customer_address["customer_zipcode"] = "";
$insert_customer_address["customer_street"] = Request::input("address");
$insert_customer_address["purpose"] = $value;
$insert_customer_address["archived"] = 0;
$insert_customer_address["created_at"] = Carbon::now();
$insert_customer_address["updated_at"] = Carbon::now();
Tbl_customer_address::insert($insert_customer_address);
}
}
}
I can't really see where I went wrong as the values went null just because they entered that if/else statement.

Laravel Request does not return result

I am using AWS and laravel 5.1.
I have two issues:
Most of the time API returns the expected result but sometimes server
doesn't return result for longer time. It might be due to the server
load(Although we don't have too much load on server).
Clients wait for few minutes and after that application crashes. Any
Advice.
If Client made an API request and before getting result, if device
loses internet connection. Server has process the data but unable to
deliver it to the client. how to handle this (Both in get as well as
post request)
Sample Code for first Part
public function psychometricResponses(Request $request)
{
$questionId=$request->get('questionId');
$answerId=$request->get('answerId');
$from = $request->has('from');
$userId = $request->has('id') ? $request->get('id') : 0;
$name = $request->has('name') ? $request->get('name') : '';
$email = $request->has('email') ? $request->get('email') : '';
$gender = $request->has('gender') ? $request->get('gender') : '';
$relationshipStatus = $request->has('relationshipStatus') ? $request->get('relationshipStatus') : '';
if($userId!=0){
$status = 1;
User::where('id',$userId)->update(['status'=>1]);
}else{
$status = 0;
}
$id = $this->calculatePersonality($questionId, $answerId, $userId, $from, $name, $email, $gender, $relationshipStatus);
return json_encode(['code'=>200,'message'=>"success",'response'=>array('personality'=>$this->_getPersonality($id),'psychometricId'=>$id,'status'=>$status)]);
}
public function calculatePersonality($questionId, $answerId, $userId, $from, $name, $email, $gender, $relationshipStatus)
{
//
$questionArray = explode(',', $questionId); //arraySize is 60
$answerArray = explode(',', $answerId); // //arraySize is 60
$this->questionAll = $this->_questionAll();
$personality = array('O'=>0,'C'=>0,'E'=>0,'A'=>0,'N'=>0);
for($i=0; $i<sizeof($answerArray);$i++){
$type = $this->_getQuestionType($questionArray[$i]);
if($type=='O'){
$personality['O'] = $answerArray[$i]=='1' ? $personality['O']+1 : $personality['O']-1;
}else if($type=='OR'){
$personality['O'] =$answerArray[$i]=='1' ? $personality['O']-1 : $personality['O']+1;
}else if($type=='C'){
$personality['C'] = $answerArray[$i]=='1' ? $personality['C']+1 : $personality['C']-1;
}else if($type=='CR'){
$personality['C'] = $answerArray[$i]=='1' ? $personality['C']-1 : $personality['C']+1;
}else if($type=='E'){
$personality['E'] = $answerArray[$i]=='1' ? $personality['E']+1 : $personality['E']-1;
}else if($type=='ER'){
$personality['E'] = $answerArray[$i]=='1'?$personality['E']-1 : $personality['E']+1;
}else if($type=='A'){
$personality['A'] = $answerArray[$i]=='1' ? $personality['A']+1 : $personality['A']-1;
}else if($type=='AR'){
$personality['A'] = $answerArray[$i]=='1' ? $personality['A']-1 : $personality['A']+1;
}else if($type=='N'){
$personality['N'] = $answerArray[$i]=='1'? $personality['N']+1 : $personality['N']-1;
}else if($type=='NR'){
$personality['N'] = $answerArray[$i]=='1' ? $personality['N']-1 : $personality['N']+1;
}
}
$mod = array();
$mod['O'] = abs($personality['O']);
$mod['C'] = abs($personality['C']);
$mod['E'] = abs($personality['E']);
$mod['A'] = abs($personality['A']);
$mod['N'] = abs($personality['N']);
arsort($mod);
$values = array_keys($mod);
$pTypeOne = $personality[$values[0]] < 0 ? $values[0].'R' : $values[0];
$pTypeTwo = $personality[$values[1]] < 0 ? $values[1].'R' : $values[1];
$pTypeThree = $personality[$values[2]] < 0 ? $values[2].'R' : $values[2];
$pTypeFour = $personality[$values[3]] < 0 ? $values[3].'R' : $values[3];
$pTypeFive = $personality[$values[4]] < 0 ? $values[4].'R' : $values[4];
$psychometricResponse = PsychometricResponse::create(array('typeA'=>$pTypeOne, 'valueA'=>$personality[$values[0]],'typeB'=>$pTypeTwo, 'valueB'=>$personality[$values[1]],
'typeC'=>$pTypeThree, 'valueC'=>$personality[$values[2]],'typeD'=>$pTypeFour, 'valueD'=>$personality[$values[3]],
'typeE'=>$pTypeFive, 'valueE'=>$personality[$values[4]],'questionId'=>$questionId,'answerId'=>$answerId, 'userId'=>$userId, 'from'=>$from,'name'=>$name,'email'=>$email, 'gender'=>$gender,'relationshipStatus'=>$relationshipStatus));
return $psychometricResponse->id;
}
private function _questionAll(){
$question = PsychometricQuestion::where('isActive',1)->get(['id','type']);
$result =array();
for($i=0;$i<sizeof($question);$i++){
$result[$question[$i]->id] = $question[$i]->type;
}
return $result;
}
private function _getQuestionType($id){
return $this->questionAll[$id];
}
private function _getPersonality($id){
$personality = PsychometricResponse::where('id',$id)->first(['typeA','typeB','typeC','typeD','typeE','valueA','valueB']);
$combined = array($personality->typeA,$personality->typeB);
sort($combined);
$combinedPersonality = PsychometricResult::where('type',$combined[0]."-".$combined[1])->first(['type','keyword','description','colorCode']); //Table PsychometricResult has 40 rows only.
$primaryPersonality = PsychometricResult::where('type',$personality->typeA)->first(['type','keyword','description','colorCode']);
$secondaryPersonality = PsychometricResult::where('type',$personality->typeB)->first(['type','keyword','description','colorCode']);
$permutation = $this->_getAllPermutation($personality);
$stylePersonality = PsychometricStyle::whereIn('type',$permutation)->get(['type','aspect','style','description']);
$primaryPercentage = round(abs($personality->valueA)/(abs($personality->valueA)+abs($personality->valueB)), 2);
$secondaryPercentage = 1 - $primaryPercentage;
return array('primaryPersonality'=>$primaryPersonality,'secondaryPersonality'=>$secondaryPersonality,'combinedPersonality'=>$combinedPersonality,
'styles'=>$stylePersonality,'primaryPercentage'=>$primaryPercentage,'secondaryPercentage'=>$secondaryPercentage);
}
private function _getAllPermutation($personality){
$combined = array($personality->typeA,$personality->typeB,$personality->typeC,$personality->typeD,$personality->typeE);
sort($combined);
$permutation = array();
for($i=0;$i<sizeof($combined);$i++){
for($j=$i+1;$j<5;$j++){
array_push($permutation,$combined[$i]."-".$combined[$j]);
}
}
return $permutation;
}

I need help to understand JSON Elements (Response Messages) from this function

I am working on a project that previously done with another developer. This project based on PHP Yii framework and mobile side is Android to get JSON messages from the web services that provided in the website.
I'm stuck in this web service function "getStamp"
I don't know what are the JSON response messages. I mean what are the string Values that I'll hold for 'stampID', 'stampName', 'stampImg'.
These are the information that I have:
request parameters:
kioskid
accesstoken
tagid
eventid
checking = 0 or 1
for failed response:
status = 0
message = error message
for success response:
status = 1
tappedStamp = the obtain stamp ID after tapping the device (if checking not equal to 1)
message = the message of the obtained stamp (if checking not equal to 1)
collectedStamp = list of collected stamp ID
If you want to use 'getStamp' web service to do the checking on how
many stamps that have been collected by the user, then you pass
'checking' as 1. If you want to use that web service to collect the
stamp of the kiosk, then you pass 'checking' as 0.
So far as what I understand from the Code and explanation that 'collectedStamp' and 'tappedStamp' are JSON Object names of a JSON Arrays
I need to know these 3 Elements (I suppose to get it from some where the names are random not real I just make it to explain to you what need)
'stampID', 'stampName','stampImg'
{ "collectedStamp" : [ { "stampID" : "1",
"stampName" : "stamp1",
"stampImg": "stamp1.png"
},
{ "stampID" : "2",
"stampName" : "stamp2",
"stampImg": "stamp2.png"
},
],
"status" : "1"
}
{ "tappedStamp" : [ { "stampID" : "1",
"stampName" : "stamp1",
"stampImg": "stamp1.png"
},
{ "stampID" : "2",
"stampName" : "stamp2",
"stampImg": "stamp2.png"
},
],
"status" : "1"
}
For Android Implementation most likely I'll use the same code that I provided in this post
Errors when getting JSON result into ListView
if you see in the web service function in that link you'll find this
$list = array();
foreach($events as $row){
$list[] = array('id'=>$row->id, 'name'=>$row->eventname);
}
$response['status'] = '1';
$response['list'] = $list;
}
which means that that the JSON response['list'] Contains 'id' and 'name' objects
and these are the String values that I add it inside ListView Adapter
I need to know the equivalent to 'id' and 'name' in this web Service
getStamp() Web Service Function:
public function actionGetStamp(){
if(isset($_POST['kioskid']) && isset($_POST['accesstoken']) && isset($_POST['tagid']) && isset($_POST['eventid']) && isset($_POST['checking'])){
$response = array();
$kiosk = Kiosk::model()->findByAttributes(array('kioskid'=>$_POST['kioskid'], 'accesstoken'=>$_POST['accesstoken']));
if(($kiosk === null || $kiosk->eventid != $_POST['eventid']) && $_POST['accesstoken'] != 'REPOST_SYNC'){
$response['status'] = '0';
$response['message'] = 'Invalid Kiosk';
} else {
$eventStation = EventStation::model()->findByAttributes(array('eventid'=>$_POST['eventid'],'deviceid'=>$_POST['kioskid']));
if($eventStation === null){
$response['status'] = '0';
$response['message'] = 'Invalid Kiosk';
} else {
$tag = EventTag::model()->findByAttributes(array('tagid'=>$_POST['tagid'], 'eventid'=>$eventStation->eventid, 'status'=>'A'));
if($tag === null || $tag->joinon == null){
$response['status'] = '0';
$response['message'] = 'Tag is not registered yet.';
} else {
$sql = 'SELECT es.id, (CASE WHEN esc.stampid IS NULL THEN 0 ELSE 1 END) collected,
(CASE WHEN es.kioskid = :kioskid THEN 1 ELSE 0 END) tapped,
es.message
FROM tap_event_stamp es
LEFT JOIN tap_event_stamp_collection esc ON es.id = esc.stampid and esc.tagid = :tagid
WHERE es.eventid = :eventid AND es.isdeleted = 0
GROUP BY es.id ORDER BY es.id
';
$params = array(':eventid'=>$_POST['eventid'], ':kioskid'=>$eventStation->id, ':tagid'=>$tag->id);
$stamps = Yii::app()->db->createCommand($sql)->queryAll(true, $params);
if(sizeof($stamps) == 0){
$response['status'] = '0';
$response['message'] = 'Invalid Request';
} else {
$feature = EventFeatures::model()->findByAttributes(array('eventid'=>$_POST['eventid'],'featureid'=>3));
if($feature === null){
$response['status'] = '0';
$response['message'] = 'Invalid Request';
} else {
$info = json_decode($feature->info, true);
$random = false;
if(isset($info['STAMPSEQ'])){
$random = $info['STAMPSEQ'] == 'R';
}
$collected = array();
$response['status'] = $_POST['checking'] == 1 ? '1' : '0';
$duplicate = false;
foreach($stamps as $stamp){
if ($stamp['tapped'] == 1 && $_POST['checking'] != 1){
$response['tappedStamp'] = $stamp['id'];
$response['message'] = $stamp['message'];
$response['status'] = '1';
$duplicate = $stamp['collected'] == 1;
} elseif($stamp['collected'] == 1){
$collected[] = $stamp['id'];
continue;
} elseif(!$random && $_POST['checking'] != 1){
if( !isset($response['tappedStamp']) ){
$response['message'] = 'You have tapped a wrong kiosk';
}
break;
}
}
if( $response['status'] == '1' ){
$response['collectedStamp'] = $collected;
if(!$duplicate && $_POST['checking'] != 1){
$newRecord = new StampCollection();
$newRecord->eventid = $_POST['eventid'];
$newRecord->tagid = $tag->id;
$newRecord->kioskid = $eventStation->id;
$newRecord->stampid = $response['tappedStamp'];
$newRecord->collectedon = time();
$newRecord->save();
}
}
if( $response['status'] == '1' && Yii::app()->params['isOffline'] && $_POST['checking'] != 1){
$params = array();
$params['tagid'] = $_POST['tagid'];
$params['eventid'] = $_POST['eventid'];
$params['kioskid'] = $_POST['kioskid'];
$params['accesstoken'] = 'REPOST_SYNC';
$model = new PendingRequest();
$model->request_url = '/ws/getStamp';
$model->request_param = json_encode($params);
$model->createdon = time();
$model->issent = 0;
$model->save();
}
}
}
}
}
}
$this->_sendResponse(200, CJSON::encode($response));
} else {
$this->_sendResponse(400);
}
}
One more question:
How can I check the web service from the Browser and pass the parameter (this Project uses Yii Framework)? So I can get JSON message either from browser.
Update:
After using "POSTMAN REST Client" I got this message
if checking = 1
{"status":"1","collectedStamp":[]}
if checking = 0
this is the HTML Code I got
https://drive.google.com/file/d/0B0rJZJK8qFz9MENzcWxhU3NPalk/edit?usp=sharing

Search based on URL varibles

I want my search to focus on variables in the URL string. Currently it uses a form based search.
It uses this
<?php
include('db.php'); // include your code to connect to DB.
$tbl_name="mobile"; //your table name
$whereClauses = array();
if (! empty($_POST['Model'])) $whereClauses[] ="model='".mysql_real_escape_string($_POST['Model'])."'";
if (! empty($_POST['Mins'])) $whereClauses[] ="minutes='".mysql_real_escape_string($_POST['Mins'])."'";
if (! empty($_POST['Texts'])) $whereClauses[] ="texts='".mysql_real_escape_string($_POST['Texts'])."'";
if (! empty($_POST['Freegifts'])) $whereClauses[] ="free_gift='".mysql_real_escape_string($_POST['Freegifts'])."'";
if (! empty($_POST['Network'])) $whereClauses[] ="network_name='".mysql_real_escape_string($_POST['Network'])."'";
if (! empty($_POST['Merchant'])) $whereClauses[] ="merchant_category='".mysql_real_escape_string($_POST['Merchant'])."'";
$where = '';
if (count($whereClauses) > 0) { $where = ' WHERE '.implode(' AND ',$whereClauses); }
$sql = mysql_query("SELECT * FROM $tbl_name".$where);
?>
However, I have added this to my page:
<?php
$model = $_GET['model']; //gets model from URL
$mins = $_GET['mins']; //gets mins from URL
$texts = $_GET['texts']; //gets mins from URL
$freegift = $_GET['free-gift']; //gets mins from URL
$network = $_GET['network']; //gets mins from URL
$plan = $_GET['plan']; //gets mins from URL
?>
It needs to be so not all variables are required. Any help would be appreciated.
Thanks in advance :)
There are a number of options that will return value or NULL:
<?php
$model = (isset($_GET['model']) ? $_GET['model'] : NULL);
$mins = (isset($_GET['mins']) ? $_GET['mins'] : NULL);
$texts = (isset($_GET['texts']) ? $_GET['texts'] : NULL);
$freegift = (isset($_GET['free-gift']) ? $_GET['free-gift'] : NULL);
$network = (isset($_GET['network']) ? $_GET['network'] : NULL);
$plan = (isset($_GET['plan']) ? $_GET['plan'] : NULL);
?>
This will get the variables from their correponding $_GET element, only if there is one set.
Alternative syntax (shorter):
<?php
$model = ($_GET['model'] ? $_GET['model'] : NULL);
$mins = ($_GET['mins'] ? $_GET['mins'] : NULL);
$texts = ($_GET['texts'] ? $_GET['texts'] : NULL);
$freegift = ($_GET['free-gift'] ? $_GET['free-gift'] : NULL);
$network = ($_GET['network'] ? $_GET['network'] : NULL);
$plan = ($_GET['plan'] ? $_GET['plan'] : NULL);
?>
Alternative (untested though):
<?php
$vars = array('model','mins','texts','free-gift','network','plan');
foreach($vars as $value) {
$$value = (isset($_GET[$value]) ? $_GET[$value] : NULL);
}
?>
EDIT:
In order to set a WHERE clause based on it, I suggest:
<?php
$vars = array('model','mins','texts','free-gift','network','plan');
foreach($vars as $value) {
$$value = (isset($_GET[$value]) ? $_GET[$value] : NULL);
unset $vars[$value]; //sweeping the NULL ones
}
$where_clause = $vars[0]; //the only remaining value after previous cleanup
?>

Categories