Search based on URL varibles - php

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
?>

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.

Update posted columns only

I am working with rest API in CodeIgniter
I am working with update API so I want to update only those columns/fields which I sent via postman,
for example, if I sent only first_name and last_name then only these columns should be updated not all columns,
but current code updating all columns, Here is my code where I am wrong?
public function update_userrecords()
{
$add_data['user_id'] = ($this->input->post('user_id') && !empty($this->input->post('user_id'))) ? $this->input->post('user_id') : NULL;
$add_data['first_name'] = ($this->input->post('first_name') && !empty($this->input->post('first_name'))) ? $this->input->post('first_name') : NULL;
$add_data['last_name'] = ($this->input->post('last_name') && !empty($this->input->post('last_name'))) ? $this->input->post('last_name') : NULL;
$add_data['password'] = ($this->input->post('password') && !empty($this->input->post('password'))) ? $this->input->post('password') : NULL;
$t=time();
$data = array(
'first_name'=>$add_data['first_name'],
'last_name'=>$add_data['last_name'],
'password'=>md5($add_data['password']),
'updated_on'=>$t,
);
$this->db->where('id',$add_data['user_id']);
$this->db->update('users', $data);
}
You can use this way
Set you input field in new array and update that array. I have added one field in $insert_data. you can add as much you want.
public function update_userrecords()
{
$add_data['user_id'] = ($this->input->post('user_id') && !empty($this->input->post('user_id'))) ? $this->input->post('user_id') : NULL;
$insert_data = [];
if($this->input->post('first_name') && !empty($this->input->post('first_name'))) {
$insert_data['first_name'] = $this->input->post('user_id');
}
$t=time();
$this->db->where('id',$add_data['user_id']);
$this->db->update('users', $insert_data);
}

laravel parse large xml file to mysql

$app = new Container;
$document = new OrchestraDocument($app);
$reader = new OrchestraReader($document);
$xml = $reader->load($path);
$xml1 = simplexml_load_file($path);
// print_r($xml1);
$json = json_encode($xml1);
$array = json_decode($json, true);
$clien =$array['cliente'];
//controll empty value
$clien = array_map(function($i) {
$i['indirizzo'] = empty($i['indirizzo']) ? '' : $i['indirizzo'];
$i['cap'] = empty($i['cap']) ? '' : $i['cap'];
$i['citta'] = empty($i['citta']) ? '' : $i['citta'];
$i['prov'] = empty($i['prov']) ? '' : $i['prov'];
$i['piva'] = empty($i['piva']) ? '' : $i['piva'];
$i['cfisc'] = empty($i['cfisc']) ? '' : $i['cfisc'];
$i['luogo_nasc'] = empty($i['luogo_nasc']) ? '' : $i['luogo_nasc'];
$i['data_nasc'] = empty($i['data_nasc']) ? '' : $i['data_nasc'];
$i['sesso'] = empty($i['sesso']) ? '' : $i['sesso'];
$i['tele'] = empty($i['tele']) ? '' : $i['tele'];
$i['mail'] = empty($i['mail']) ? '' : $i['mail'];
$i['cell'] = empty($i['cell']) ? '' : $i['cell'];
$i['cod_card'] = empty($i['cod_card']) ? '' : $i['cod_card'];
$i['cod_card1'] = empty($i['cod_card1']) ? '' : $i['cod_card1'];
$i['punti_card'] = empty($i['punti_card']) ? '' : $i['punti_card'];
return $i;
}, $clien);
$collection = collect($clien);
$collection1 = $collection->chunk(500);
i'm try to import a large xml file into my mysql database.
i'm load my xml file into object, i'm tranform this object into array, i'm control the empty value, and ok.
Now because i have a large query i tranform my array in laravel collection and chunk for isert 500 records at a time, but now i have a new object $collection1. How i enter the query? i have to trasform again in array?
for($i=0;$i<count($collection1);$i++) {
var_dump($collection1[$i]);
$collection1[$i]= stdToArray;
DB::connection()->disableQueryLog();
DB::table('clientis')->insert($collection1[$i]);
foreach( $collection1[$i] as $k=>$v){
var_dump($v);
}
}
thi code don't work
Looking at your code you don't need to create a collection. You can just array_chunk the data:
/*
$collection = collect($clien);
$collection1 = $collection->chunk(500);
*/
$collection = array_chunk($clien, 500, true);

Sync phonebook using 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).

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;
}

Categories