Call to undefined method stdClass::save() in yii framework - php

I am building chats pop up where one user will initiate conversation with another user.
In my initiatechat function i have the following error Call to undefined method stdClass::save().
Look at codes and find THIS SAVE FUNCTION ==>> the save() function that throw error.
If two users have already initiated conversation this error does not happen.
public function actionInitiatechat() {
if (isset($_POST)){
//$message = Myclass::checkPostvalue($_POST['message']) ? $_POST['message'] : "";
$senderId = Myclass::checkPostvalue($_POST['sender']) ? $_POST['sender'] : "";
$receiverId = Myclass::checkPostvalue($_POST['receiver']) ? $_POST['receiver'] : "";
$messageType = Myclass::checkPostvalue($_POST['messageType']) ? $_POST['messageType'] : "";
$sourceId = Myclass::checkPostvalue($_POST['sourceId']) ? $_POST['sourceId'] : "";
$timeUpdate = time();
$message = $_POST['message'];
$Products = Products::model()->findByPk($sourceId);
if(isset($Products) && $Products->approvedStatus == 0)
{
echo "error";
}
else
{
$criteria = new CDbCriteria;
$criteria->condition = "(user1 = '$senderId' AND user2 = '$receiverId') OR (user1 = '$receiverId' AND user2 = '$senderId')";
$chatModel = Chats::model()->find($criteria);
$encodeMsg = urlencode($message);
if (empty($chatModel)){
$newChat = new Chats();
$newChat->user1 = $senderId;
$newChat->user2 = $receiverId;
$newChat->lastMessage = $encodeMsg;
$newChat->lastToRead = $receiverId;
$newChat->lastContacted = $timeUpdate;
$newChat->save();
$criteria = new CDbCriteria;
$criteria->condition = "(user1 = '$senderId' AND user2 = '$receiverId') OR (user1 = '$receiverId' AND user2 = '$senderId')";
$chatModel = Chats::model()->find($criteria);
}
$chatModel->lastContacted = $timeUpdate;
if ($chatModel->user1 == $senderId){
$chatModel->lastToRead = $chatModel->user2;
}else{
$chatModel->lastToRead = $chatModel->user1;
}
$chatModel->lastMessage = $encodeMsg;
THIS SAVE FUNCTION ==>> $chatModel->save();
$messageModel = new Messages();
$messageModel->message = $encodeMsg;
$messageModel->messageType = $messageType;
$messageModel->senderId = $senderId;
$messageModel->sourceId = $sourceId;
$messageModel->chatId = $chatModel->chatId;
$messageModel->createdDate = $timeUpdate;
$messageModel->save();
}
echo "success";
}
}
else
{
echo "failed";
}
}

The statement below is presumably returning a "bare" object of type stdClass, which doesn't define a save() method, hence your error.
$chatModel = Chats::model()->find($criteria);
Run var_dump($chatModel); immediately after this statement and see what type of object you're getting.

Related

Check duplication while uploading to database

I need to find duplicated details in the existing table while uploading a Excel file that contains some details,i need to find that by phone number and customer name. I am using mattexcel to upload the data into database.
I don't want to insert that details if it is in there but other details must insert into that table
Controller
public function importExcel(Request $request)
{
if ($request->hasFile('import_file')) {
Excel::load($request->file('import_file')->getRealPath(), function ($reader) {
foreach ($reader->toArray() as $key => $row) {
$data['customername'] = $row['customername'];
$data['chassis'] = $row['chassis'];
$data['model'] = $row['model'];
$data['branchcode'] = $row['branchcode'];
$data['delivery'] = $row['delivery'];
$data['customerid'] = $row['customerid'];
$data['phone'] = $row['phone'];
$data['invoicedate'] = $row['invoicedate'];
$data['dse'] = $row['dse'];
$data['branch'] = $row['branch'];
$data['finance'] = $row['finance'];
$data['dono'] = $row['dono'];
$data['invoice'] = $row['invoice'];
$data['zsm'] = $row['zsm'];
$data['sm'] = $row['sm'];
$data['agm'] = $row['agm'];
$data['dsecode'] = $row['dsecode'];
$data['address'] = $row['address'];
$data['email'] = $row['email'];
$data['color'] = $row['color'];
$data['extendedwarrenty'] = $row['extendedwarrenty'];
$data['autocaddownload'] = $row['autocaddownload'];
$data['numberplate'] = $row['numberplate'];
$data['mcpstatus'] = $row['mcpstatus'];
$data['plandt'] = $row['plandt'];
$data['planok'] = $row['planok'];
$data['fasttag'] = $row['fasttag'];
// $data['settilment_pdf_path'] = $row['settilment_pdf_path'];
$data['rcstatus'] = $row['rcstatus'];
$branch = Branch::where([['branch_code', $row['branchcode']], ['status', 0]])->first();
$registration_id = Registration::orderBy('registration_id', 'desc')->take(1)->get();
if (count($registration_id) > 0) {
$regid = $registration_id[0]->registration_id;
$regid = $regid + 1;
} else {
$regid = 1;
}
$register = new Registration();
$register->registration_id = $regid;
$register->customername = $row['customername'];
$register->chassis = $row['chassis'];
$register->model = $row['model'];
$register->branchcode = $row['branchcode'];
$register->delivery = $row['delivery'];
$register->customerid = $row['customerid'];
$register->phone = $row['phone'];
$register->invoicedate = $row['invoicedate'];
$register->dse = $row['dse'];
$register->branch = $row['branch'];
$register->finance = $row['finance'];
$register->dono = $row['dono'];
$register->invoice = $row['invoice'];
$register->zsm = $row['zsm'];
$register->sm = $row['sm'];
$register->agm = $row['agm'];
$register->dsecode = $row['dsecode'];
$register->address = $row['address'];
$register->email = $row['email'];
$register->color = $row['color'];
$register->extendedwarrenty = $row['extendedwarrenty'];
$register->autocaddownload = $row['autocaddownload'];
$register->numberplate = $row['numberplate'];
$register->mcpstatus = $row['mcpstatus'];
$register->plandt = $row['plandt'];
$register->planok = $row['planok'];
$register->fasttag = $row['fasttag'];
$register->rcstatus = $row['rcstatus'];
$register->dealership = $branch->dealership_id;
$register->zone = $branch->zone_id;
$register->dh = $branch->dh_id;
$register->status = '0';
$register->created_user_id = Session::get('created_id');
$register->save();
$regidn = Registration::orderBy('registration_id', 'desc')->get();
$regidd = $regidn[0]->registration_id;
$ssitrack = new Ssi_track();
$ssitrack->registration_id = $regid;
$ssitrack->ssi_track_id = $regid;
$ssitrack->save();
$ssitrackk = Ssi_track::orderBy('ssi_track_id', 'desc')->get();
$ssitrackk = $ssitrackk[0]->registration_id;
}
});
}
return back()->with('success', 'Your File Is Successfully Uploaded To Database!');
}
Option 1. You can add unique values combination in migration.
Schema::table('your_table_name', function (Blueprint $table) {
$table->unique(['phone ','customername ']);
});
This won't let you insert same combination values for these column combination, however it also throws error stopping you import function.
Option 2 (Better).
Check if value already exits and ignore import for that column.
$old_customer = Regiter::where('phone', $row['phone'])->where('customername', $customername )->first();
//Inser only if customer not found
if(is_null($old_customer))
{
//INSERT QUERY
}
To decrease number of query you can pluck name and phone with single query or use any other optimization tricks.

Undefined Variable - Works

I have a script which updates a date field in my database. (purchased).
I'm also using that data in another part which updates a second date field which takes the input date and add's 6 years $duedate. It works just fine but I get the Undefined Variable error for the variable purchased.
$duedate = new DateTime($purchased);
$duedate->add(new DateInterval('P6Y'));
I have tried defining it using the below, but it stops the second field being updated and does not throw any errors.
$duedate = new DateTime($_POST['purchased']);
$duedate->add(new DateInterval('P6Y'));
$purchased = "";
$duedate = new DateTime($purchased);
$duedate->add(new DateInterval('P6Y'));
$purchased = null;
$duedate = new DateTime($purchased);
$duedate->add(new DateInterval('P6Y'));
$purchased = isset($_POST['purchased']) ? $_POST['purchased'] : '';
$duedate = new DateTime($purchased);
$duedate->add(new DateInterval('P6Y'));
$purchased = !empty($_POST['purchased']) ? $_POST['purchased'] : '';
$duedate = new DateTime($purchased);
$duedate->add(new DateInterval('P6Y'));
Code
$barcode = $_GET['barcode'];
$stmt = $conn->prepare("SELECT * FROM assets WHERE barcode=:barcode");
$stmt->execute(array(":barcode"=>$barcode));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
if (isset($_POST['update'])) {
$category = isset($_POST['category']) ? $_POST['category'] : null;
$manufactuer = isset($_POST['manufactuer']) ? $_POST['manufactuer'] : null;
$model = isset($_POST['model']) ? $_POST['model'] : null;
$serial = isset($_POST['serial']) ? $_POST['serial'] : null;
$itemcondition = isset($_POST['itemcondition']) ? $_POST['itemcondition'] : null;
$locationb = isset($_POST['locationb']) ? $_POST['locationb'] : null;
$locationr = isset($_POST['locationr']) ? $_POST['locationr'] : null;
$comments = isset($_POST['comments']) ? $_POST['comments'] : null;
$purchased = isset($_POST['purchased']) ? $_POST['purchased'] : null;
$retired = isset($_POST['retired']) ? $_POST['retired'] : null;
$stolen = isset($_POST['stolen']) ? $_POST['stolen'] : null;
$latest = isset($_POST['latest']) ? $_POST['latest'] : null;
$due = isset($_POST['due']) ? $_POST['due'] : null;
$sql_part = array();
$prepare = array();
if ($category){
$sql_part[] = 'category = :category';
$prepare[':category'] = $category;
}
if($manufactuer){
$sql_part[] = 'manufactuer = :manufactuer';
$prepare[':manufactuer'] = $manufactuer;
}
if($model){
$sql_part[] = 'model = :model';
$prepare[':model'] = $model;
}
if($serial){
$sql_part[] = 'serial = :serial';
$prepare[':serial'] = $serial;
}
if($itemcondition){
$sql_part[] = 'itemcondition = :itemcondition';
$prepare[':itemcondition'] = $itemcondition;
}
if($locationb){
$sql_part[] = 'locationb = :locationb';
$prepare[':locationb'] = $locationb;
}
if($locationr){
$sql_part[] = 'locationr = :locationr';
$prepare[':locationr'] = $locationr;
}
if($comments){
$sql_part[] = 'comments = :comments';
$prepare[':comments'] = $comments;
}
if($purchased){
$sql_part[] = 'purchased = :purchased';
$prepare[':purchased'] = $purchased;
}
if($retired){
$sql_part[] = 'retired = :retired';
$prepare[':retired'] = $retired;
}
if($stolen){
$sql_part[] = 'stolen = :stolen';
$prepare[':stolen'] = $stolen;
}
if($latest){
$sql_part[] = 'latest = :latest';
$prepare[':latest'] = $latest;
}
if($due){
$sql_part[] = 'due =:due';
$prepare[':due'] = $due;
}
$prepare[':barcode'] = $barcode;
if(count($sql_part)){
$sql = 'UPDATE assets SET ';
$sql .= implode(', ', $sql_part);
$sql .= ' WHERE barcode = :barcode';
$stmt = $conn->prepare($sql);
if($stmt){
$result = $stmt->execute($prepare);
$count = $stmt->rowCount();
header('Location: ./usearch.php');
exit;
}
}
}
$duedate = new DateTime($purchased);
$duedate->add(new DateInterval('P6Y'));
<input type="hidden" name="due" value="<?php echo $duedate->format('Y-m-d'); ?>">
The file is 261 lines so I've included the relevant segments and can add full file if needed.
These lines at the end of your file:
$duedate = new DateTime($purchased);
$duedate->add(new DateInterval('P6Y'));
<input type="hidden" name="due" value="<?php echo $duedate->format('Y-m-d'); ?>">
are throwing that undefined variable notice because it's placed outside conditionals and as soon as the page is loaded.
That's what I make out of all this.
I posted this, since I made a comment much earlier about it.
Therefore, use a conditional statement/ternary operator.
It will do its job as soon as there is a value for it.
Your code is a bit odd in that you seem to be using the page both in cases where you're updating and in cases where you're not.
Try this:
<?php
$barcode = $_GET['barcode'];
$stmt = $conn->prepare("SELECT * FROM assets WHERE barcode=:barcode");
$stmt->execute(array(":barcode" => $barcode));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (isset($_POST['update'])) {
$purchased = isset($_POST['purchased']) ? $_POST['purchased'] : null;
$due = isset($_POST['due']) ? $_POST['due'] : null;
$sql_part = array();
$prepare = array();
if ($purchased) {
$sql_part[] = 'purchased = :purchased';
$prepare[':purchased'] = $purchased;
}
if ($due) {
$sql_part[] = 'due =:due';
$prepare[':due'] = $due;
}
$prepare[':barcode'] = $barcode;
if (count($sql_part)) {
$sql = 'UPDATE assets SET ';
$sql .= implode(', ', $sql_part);
$sql .= ' WHERE barcode = :barcode';
$stmt = $conn->prepare($sql);
if ($stmt) {
$result = $stmt->execute($prepare);
$count = $stmt->rowCount();
header('Location: ./usearch.php');
exit;
}
}
}
if (isset($purchased)) {
$purchasedDate = new DateTime($purchased);
}
if (isset($due)) {
$duedate = new DateTime($due);
} else {
$duedate = new DateTime($purchased?:"now");
$duedate->add(new DateInterval('P6Y'));
}
?>
<input type = "hidden" name = "due" value = "<?php echo $duedate->format('Y-m-d'); ?>">

edit text value pass wrong to the server in Hebrew langaue

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

php - class property not returning value

I am wondering my class property $friend_username does not returning its value either it is public.
update
class Feed {
public static $friend_username;
// ONLINE FRIENDS LOGIC
public function online_friends(){
$friendsHTML = '';
$countOnlineFriends = '';
if(GetFriends($GLOBALS['log_username']) != false) {
$all_friends = GetFriends($GLOBALS['log_username']);
$orLogic = '';
foreach($all_friends as $key => $user){
if(IsBlocked($GLOBALS['log_username'],$user,true) == false){
$orLogic .= "username='$user' OR ";
}
}
$orLogic = chop($orLogic, "OR ");
$sql = "SELECT username, avatar, logged_in FROM users WHERE ($orLogic) AND logged_in = 1";
$query = mysqli_query($GLOBALS['db_conx'], $sql);
$friend_loggedIn = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$this->friend_username = $row["username"];
$friend_avatar = $row["avatar"];
$friend_loggedIn[] = $row["logged_in"];
$friend_pic = userImage($this->friend_username,$friend_avatar,'42','42',$link = false,$up = true);
$friendsHTML .= '<li><a href="#" onClick="chatbox(\''.$this->friend_username.'\',\''.getName($this->friend_username,true).'\');return false;">'.$friend_pic.' '.getName($this->friend_username,true).'</li>';
$countFriends = count($friend_loggedIn);
$countOnlineFriends = ($countFriends > 0) ? '<span class="online_friends animated">'.$countFriends.'</span>' : '';
}
}else{
$friendsHTML = 'No friends';
}
return "$countOnlineFriends|$friendsHTML";
}
public function update_chat() {
$id = '';
$messages = '';
$randUser = '';
$user = sanitize($this->friend_username);
$sql = "SELECT * FROM pm_chat WHERE (sender='$GLOBALS[log_username]' AND receiver='$user') OR (sender='$user' AND receiver='$GLOBALS[log_username]') ORDER BY datetime DESC";
$result = mysqli_query($GLOBALS['db_conx'],$sql) or die(mysqli_error($GLOBALS['db_conx']));
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$user1 = $row['sender'];
$user2 = $row['receiver'];
$message = parseData($row['message']);
$did_read = $row['did_read'];
$datetime = $row['datetime'];
if ($user1 != $GLOBALS['log_username']) {
$randUser = $user1;
}elseif ($user2 != $GLOBALS['log_username']) {
$randUser = $user2;
}
if ($user1 == $GLOBALS['log_username'] && $user2 != $GLOBALS['log_username']) {
$messages .= '<li class="row" id="pm_row_'.$id.'"><div class="me">'.$message.'</div></li>';
}else{
$messages .= '<li class="row" id="pm_row_'.$id.'">'.userImage($randUser,getAvatar($randUser),28,28,$link = true,$up = true).'<div class="userfrnd">'.$message.'</div></li>';
}
}
return $this->friend_username."$id|$messages|$randUser";
// this is for ^^^^^^^ testing purpose
}
}
here is the other file where I am calling the other class method. And its content-type is text/event-stream
class update_chat extends SSEEvent {
public function update(){
//Here's the place to send data
$feed = new Feed();
return $feed->update_chat();
}
public function check(){
//Here's the place to check when the data needs update
return true;
}
}
Any idea or suggestion why this problem persist ?
thanks in advance.
If you are calling bar() in another file and then creating a new Foo in otherClass, you are not referencing the same instance of Foo. Either make $friend_username static and call it statically
public static $friend_username;
public function update(){
//Here's the place to send data
return Foo::$friend_username;
}
or at least make the function static
public static function bar() {}
public function update(){
//Here's the place to send data
return Foo::bar();
}
or pass in the instance of Foo to the function
public function update(Foo $Foo){
//Here's the place to send data
return $Foo->bar();
}
If you want to call a static method from within the same class, you have to use the self identifier (self::$var)
class Feed {
public static $friend_username = array();
// ONLINE FRIENDS LOGIC
public function online_friends(){
$friendsHTML = '';
$countOnlineFriends = '';
if(GetFriends($GLOBALS['log_username']) != false) {
$all_friends = GetFriends($GLOBALS['log_username']);
$orLogic = '';
foreach($all_friends as $key => $user){
if(IsBlocked($GLOBALS['log_username'],$user,true) == false){
$orLogic .= "username='$user' OR ";
}
}
$orLogic = chop($orLogic, "OR ");
$sql = "SELECT username, avatar, logged_in FROM users WHERE ($orLogic) AND logged_in = 1";
$query = mysqli_query($GLOBALS['db_conx'], $sql);
$friend_loggedIn = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
array_push(self::$friend_username, $row["username"]);
$friend_avatar = $row["avatar"];
$friend_loggedIn[] = $row["logged_in"];
$friend_pic = userImage(self::$friend_username,$friend_avatar,'42','42',$link = false,$up = true);
$friendsHTML .= '<li><a href="#" onClick="chatbox(\''.self::$friend_username.'\',\''.getName(self::$friend_username,true).'\');return false;">'.$friend_pic.' '.getName(self::$friend_username,true).'</li>';
$countFriends = count($friend_loggedIn);
$countOnlineFriends = ($countFriends > 0) ? '<span class="online_friends animated">'.$countFriends.'</span>' : '';
}
}else{
$friendsHTML = 'No friends';
}
return "$countOnlineFriends|$friendsHTML";
}
public function update_chat() {
$id = '';
$messages = '';
$randUser = '';
$user = Feed::$friend_username;
foreach ($user as $key => $value) {
$user[$key] = sanitize($value);
}
//I leave it up to you to figure out how you want to deal with the array of users in this next line
$sql = "SELECT * FROM pm_chat WHERE (sender='$GLOBALS[log_username]' AND receiver='$user') OR (sender='$user' AND receiver='$GLOBALS[log_username]') ORDER BY datetime DESC";
$result = mysqli_query($GLOBALS['db_conx'],$sql) or die(mysqli_error($GLOBALS['db_conx']));
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$user1 = $row['sender'];
$user2 = $row['receiver'];
$message = parseData($row['message']);
$did_read = $row['did_read'];
$datetime = $row['datetime'];
if ($user1 != $GLOBALS['log_username']) {
$randUser = $user1;
}elseif ($user2 != $GLOBALS['log_username']) {
$randUser = $user2;
}
if ($user1 == $GLOBALS['log_username'] && $user2 != $GLOBALS['log_username']) {
$messages .= '<li class="row" id="pm_row_'.$id.'"><div class="me">'.$message.'</div></li>';
}else{
$messages .= '<li class="row" id="pm_row_'.$id.'">'.userImage($randUser,getAvatar($randUser),28,28,$link = true,$up = true).'<div class="userfrnd">'.$message.'</div></li>';
}
}
return Feed::$friend_username."$id|$messages|$randUser";
// this is for ^^^^^^^ testing purpose
}
}
Well, since your are using the method mysqli_fetch_array, could it be that more than one element is returned and that the last one is empty?
BTW, I don't understand why you are making a single variable attribution inside a while statement. Supposedly, the last running (if some) will overwrite the variable's value.
Another observation, on the second code. If you are calling the bar() method right off the bat, shoudn't the variable be empty anyway? I understand that $friend_username is only assigned inside the foo() method.

Create Booking with Temando API

I am testing Temando API and trying to create a Booking. I have followed the instructions given by their manual Temando API R1_11 Developers Guide.
My problem is that when I create the call makeBookingByRequest with the following required information:
Anythings, Anywhere, Anytime, General, Origin, Destination, Quote, Payment, Instructions, Comments, Promotion Code.
It returns an error 500 : Internal Server Error. If it's something got to do with the permission, I have already fixed that.
By the way here's the rest of my code:
ini_set("soap.wsdl_cache_enabled", "1");
$client = new SoapClient("https://training-api.temando.com/schema/XXXX/server.wsdl", array('soap_version' => SOAP_1_2));
$username = "xxxxxxxxxx";
$password = "xxxxxxxxxx";
$headerSecurityStr = "<Security><UsernameToken><Username>".$username."</Username><Password>".htmlentities($password)."</Password></UsernameToken></Security>";
$headerSecurityVar = new SoapVar($headerSecurityStr, XSD_ANYXML);
$soapHeader = new SoapHeader('wsse:http://schemas.xmlsoap.org/ws/2002/04/secext', 'soapenv:Header', $headerSecurityVar);
$client->__setSoapHeaders(array($soapHeader));
$destination = array();
$destination["destinationCountry"] = "AU";
$destination["destinationCode"] = "2000";
$destination["destinationSuburb"] = "Sydney";
$destination["destinationIs"] = "Residence";
$destination["destinationResPostalBox"] = "N";
$destination["destinationResUnattended"] = "N";
$destination["destinationResInside"] = "N";
$destination["destinationResLimitedAccess"] = "N";
$destination["destinationResHeavyLift"] = "N";
$origin = array();
$origin["originDescription"] = "ABC Suppliers";
$origin["originBusUnattended"] = "N";
$origin["originBusInside"] = "N";
$origin["originBusHeavyLift"] = "N";
$origin["originBusTailgateLifter"] = "N";
$origin["originBusContainerSwingLifter"] = "N";
$quote = array();
$quote["totalPrice"] = "110.00";
$quote["basePrice"] = "100.00";
$quote["tax"] = "10.00";
$quote["currency"] = "AUD";
$quote["deliveryMethod"] = "Off-peak";
$quote["etaFrom"] = "2";
$quote["etaTo"] = "3";
$quote["guaranteedEta"] = "Y";
$payment = array();
$payment["paymentType"] = "Credit Card";
$payment["cardType"] = "Mastercard";
$payment["cardExpiryDate"] = "05-2010";
$payment["cardNumber"] = "5163190000000000";
$payment["cardName"] = "JANE DOE";
$comments = "No Comment";
$reference = "ABC200000";
$makeBookingByRequest = array();
$makeBookingByRequest["anything"] = $anything1;
$makeBookingByRequest["anytime"] = $anytime;
$makeBookingByRequest["anywhere"] = $anywhere;
$makeBookingByRequest["general"] = $general;
$makeBookingByRequest["origin"] = $origin;
$makeBookingByRequest["destination"] = $destination;
$makeBookingByRequest["quote"] = $quote;
$makeBookingByRequest["payment"] = $payment;
$makeBookingByRequest["instructions"] = $instructions;
$makeBookingByRequest["comments"] = $comments;
$makeBookingByRequest["reference"] = $reference;
$anythings = array();
$anything1 = array();
$anything1["class"] = "Freight";
$anything1["mode"] = "Less than load";
$anything1["packaging"] = "Carton";
$anything1["qualifierFreightGeneralFragile"] = "N";
$anything1["distanceMeasurementType"] = "Centimetres";
$anything1["weightMeasurementType"] = "Kilograms";
/** get the data below from POST DATA **/
$anything1["length"] = "30";
$anything1["width"] = "10";
$anything1["height"] = "10";
$anything1["weight"] = "10";
$anything1["quantity"] = "1";
$anything1["description"] = "Contains bottle lids and liquors.";
/*****************/
array_push($anythings, $anything1);
$anywhere = array();
$anywhere["itemNature"] = "Domestic";
$anywhere["itemMethod"] = "Door to Door";
$anywhere["originCountry"] = "AU";
$anywhere["originCode"] = "4000";
$anywhere["originSuburb"] = "Brisbane";
$anywhere["originIs"] = "Business";
$anywhere["originBusUnattended"] = "N";
$anywhere["originBusDock"] = "Y";
$anywhere["originBusForklift"] = "N";
$anywhere["originBusLoadingFacilities"] = "N";
$anywhere["originBusInside"] = "N";
$anywhere["originBusLimitedAccess"] = "N";
$anywhere["originBusHeavyLift"] = "N";
$anywhere["originBusTailgateLifter"] = "N";
$anywhere["originBusContainerSwingLifter"] = "N";
$anywhere["destinationCountry"] = "AU";
$anywhere["destinationCode"] = "2000";
$anywhere["destinationSuburb"] = "Sydney";
$anywhere["destinationIs"] = "Residence";
$anywhere["destinationResPostalBox"] = "N";
$anywhere["destinationResUnattended"] = "N";
$anywhere["destinationResInside"] = "N";
$anywhere["destinationResLimitedAccess"] = "N";
$anywhere["destinationResHeavyLift"] = "N";
$anytime = array();
$anytime["readyDate"] = "2012-06-01";
$anytime["readyTime"] = "PM";
$general = array();
$general["goodsValue"] = "2000.00";
call method:
try{
$makeBookingByRequestResponse = $client->makeBookingByRequest($makeBookingByRequest);
p($makeBookingByRequestResponse);
}catch (SoapFault $exception){
p($exception);
// Nothing is done with the exception yet. Will be processed later in the display code.
}
function p($arr){
echo '<pre>';
print_r($arr);
echo '</pre>';
}
Is there anyone who has experience in using Temando API? Any help would be appreciated.
Try to create your SOAP request using soapUI. It's a free software very useful to deal with SOAP web services. When it works, you can focus on build this request using PHP.

Categories