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
Related
I am making a quiz module in which there is only one user for now. So if the new user plays a quiz then the user will be added to the database and if the existed user is playing the quiz the we just have to update the coins
I have made a logic but it doesn't works for me
public function story1_home_coin(Request $request)
{
$coins = $request->input('coins');
$user_id = Auth::user()->id;
$activity_users = activity_users::all();
$found = false;
foreach($activity_users as $activity_user){
if($user_id == $sctivity_user->user_id)
{
$found= true;
}
else{
$found = false;
}
}
if($found = true){
activity_users::where([
['user_id', '=', $user_id],
['activity_id', '=', 1]
])->update(['coins' => $coins]);
}
else{
$newactivity_users = new activity_users;
$newactivity_users->userid = $user_id;
$newactivity_users->activity_id = 1;
$newactivity_users->coins = $coins;
$newactivity_users->save();
}
}
Your logic should be like this:
public function story1_home_coin(Request $request)
{
$coins = $request->input('coins');
$user_id = Auth::user()->id;
$activity_users = activity_users::where('user_id',$user_id);
if($activity_users->count()){
activity_users::where([
['user_id', '=', $user_id],
['activity_id', '=', 1]
])->update(['coins' => $coins]);
}else{
$newactivity_users = new activity_users;
$newactivity_users->userid = $user_id;
$newactivity_users->activity_id = 1;
$newactivity_users->coins = $coins;
$newactivity_users->save();
}
}
In your logic, you are checking the user by looping on to the data after fetching all the data, while you should only fetch the related user.
There are two problems in your code that lead to an unexpected behaviour.
First, in your foreach-loop, you're not dropping out of the loop when you have found a matching user_id, hence you're (almost) always setting $found to false.
For example, if you're looking for user_id 3, you'd go through your users 1-5.
user_id == 1 -> $found = false
user_id == 2 -> $found = false
user_id == 3 -> $found = true
user_id == 4 -> $found = false
user_id == 5 -> $found = false
This can be resolved by using a break; in your loop, like this:
foreach($activity_users as $activity_user){
if($user_id == $sctivity_user->user_id)
{
$found= true;
break;
}
}
Second problem is the line where you check the $found variable. You're actually not checking the variable, you're setting the variable:
if($found = true){
compared to this
if($found == true){
I am inserting a serial number in a table that is increment by one always but when multiple request is coming in same time it is inserting same serial number for different requests.I am using mysql database.
I know i am fetching the max serial number too early in the code and if request is come in same time so it will fetching same serial number for both. is it good idea to update serial number after all work done. what if inserting a record for new request and updating the serial number for previous one is in same time.
public function add(){
$session = $this->request->session();
$company_id = $session->read('Admin.company_id');
$emp_id = $session->read('Admin.emp_id');
$user_email_id = $session->read('Admin.email_id');
$employee_name = $session->read('Admin.employee_name');
$conn = ConnectionManager::get('default');
if ($this->request->is('post')) {
try{
$conn->begin();
$department = $this->request->data['department'];
$data = $this->request->data;
if(!array_key_exists('is_requisition_for_contractor', $data)){
$is_requisition_for_contractor = 0;
} else {
$is_requisition_for_contractor = $data['is_requisition_for_contractor'];
}
if(!array_key_exists('is_requisition_for_employee', $data)){
$is_requisition_for_employee = 0;
} else {
$is_requisition_for_employee = $data['is_requisition_for_employee'];
}
if(!array_key_exists('is_boulder_requisition', $data)){
$is_requisition_for_boulder = 0;
} else {
if($data['is_boulder_requisition'] == ''){
$is_requisition_for_boulder = 0;
} else {
$is_requisition_for_boulder = $data['is_boulder_requisition'];
}
}
$is_requisition_for_plant = 0;
if(!array_key_exists('is_plant_requisition', $data)){
$is_requisition_for_plant = 0;
} else {
if($data['is_plant_requisition'] == ''){
$is_requisition_for_plant = 0;
} else {
$is_requisition_for_plant = $data['is_plant_requisition'];
}
}
if(array_key_exists("files",$this->request->data)) {
$files = $this->request->data['files'];
if (count($files)) {
$files_uploading_response = $this->uploadMultipleFiles($files, 'files/requisitions/');
}
}
$last_material_insert_id = '';
if($this->request->data('material_id')[0] == ''){
if($this->request->data('department') == 1){
$type = 1;
} elseif($this->request->data('department') == 3){
$type = 3;
} elseif($this->request->data('department') == 2){
$type = 2;
}
if($this->request->data('department') == 1 || $this->request->data('department') == 3){
$conn->execute("INSERT INTO material (material_name, material_type_id, company_id, status, is_approved_by_admin) VALUES (?,?,?,?,?)",[$this->request->data('material_name'), $type, $company_id, 1,0]);
$last_material_insert_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
} elseif($this->request->data('department') == 2) {
//todo for unapproved material
$conn->execute("INSERT INTO material (part_no, material_type_id, company_id, status, is_approved_by_admin,unique_category_id) VALUES (?,?,?,?,?,?)",[$this->request->data('part_no')[0], $type, $company_id, 1,0,$this->request->data('unique_category_id')[0]]);
$last_material_insert_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
}
}
// here i am fatching max serial number from table
$requistion_number = $conn->execute("SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no FROM requisition WHERE site_id = ?",[$this->request->data('site_id')])->fetchAll('assoc');
$Requisition = TableRegistry::get('requisition');
$requisition = $Requisition->newEntity();
$requisition->registered_on = $this->request->data['date'];
$requisition->department_id = $this->request->data('department');
$requisition->site_id = $this->request->data('site_id');
$requisition->issues_to_id = $this->request->data['prepared_by_id'];
$requisition->prepared_by_id = $this->request->data['prepared_by_id'];
$requisition->approved_by_id = $this->request->data['hod_id'];
$requisition->hod_id = $this->request->data['hod_id'];
$requisition->is_diesel_requisition_for_employee = $is_requisition_for_employee;
$requisition->is_diesel_requisition_for_contractor = $is_requisition_for_contractor;
$requisition->is_requisition_for_boulder = $is_requisition_for_boulder;
$requisition->is_requisition_for_plant = $is_requisition_for_plant;
if(array_key_exists('for_tanker_stock', $this->request->data)) {
$requisition->for_tanker_stock = 1;
}
if($last_material_insert_id != ''){
$requisition->is_material_approved_by_admin = 0;
}
$requisition->status = 1;
$site_id = $this->request->data['site_id'];
$requisition->requisition_no = $requistion_number[0]['requisition_no'] + 1;
$requistionnumber = $requistion_number[0]['requisition_no'] + 1;
$saveRequsition = $Requisition->save($requisition);
$conn->commit();
}
I am expecting the output different serial number for each request.any optimise way to do this. thanks in advance.
Ok, how about the same strategy, setting the $requisition_number after the row has been inserted (see my other answer), but using a single query with the same method you use to determine the new requisition id:
$conn->execute("UPDATE requisition
SET requisition_no = (SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no FROM requisition WHERE site_id = ?) + 1",
[$this->request->data('site_id')]);
The idea here is that a single query will be executed in one step, without another, similar query, being able to interfere.
What you currently do is to first get the old requistion number like this:
$requistion_number = $conn->execute("SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no
FROM requisition WHERE site_id = ?",[$this->request->data('site_id')])->fetchAll('assoc');
and then increase it before you save and commit.
My suggestion is to not set the $requistion_number at all before you save and commit the requisition row, but to determine the $requistion_number afterwards.
You now wonder how?
Well, you need to count the total number of requisition rows in the table for the site the requisition is for, and add one, like this:
$last_requisition_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
$site_id = $this->request->data('site_id');
$requisition_number = $conn->execute("SELECT COUNT(*) AS requisitionsCount
FROM requisition
WHERE <primary_key> <= ? AND
site_id = ?",
[$last_requisition_id, $site_id]) + 1;
$conn->execute("UPDATE requisition
SET requisition_no = ?
WHERE <primary_key> <= ?",
[$requisition_number, $last_requisition_id]);
I know this code is not working. The $requisition_number will probably contain an array with the requisitionsCount as a value, but you can correct that.
Because you're using data that is already present in the database table you don't run the risk that two rows will get the same $requisition_number. The assumption here is that requisitions are never deleted.
okay I'm getting the error Call to undefined method MyDbCon and I'm a newbie so please assist me, what am I doing wrong here? be gentle lol
use Zend\Db\Sql\Select;
function getStudentsByMst(&$response,$mst_id,$stud_id=true,$now=true)
{ if(!ctype_digit($mst_id))
{ $response = array(
'code' => HTTP_Status::BAD_REQUEST,
'message' => 'Registration ID cannot be digits only'
);
return false;
}
}
include_once('credentials.db.php');
if(empty($_POST['stud_id']) == FALSE)
{
$barcode = htmlentities($_POST['stud_id']);
//checking if the barcode exist in the database
$dbh=new MyDbCon;
$barcode_check = $dbh->query("select * from usats where stud_id='$stud_enrolmentno'");
//extracting the status of the item
if($barcode_check->rowCount() > 0)
{
while($row = $barcode_check->fetch(PDO::FETCH_OBJ))
{
$presence = $row->presence;
}
}
if($barcode_check->rowCount() > 0 && $presence == '1')
{
//updating the database table barcode for student presence/absence
$addAttd = $dbh->exec("UPDATE usats SET status='0' where stud_id= '$stud_enrolmentno'");
if($addAttd > 0)
{
echo "<script> alert('Successful');</script>";
}
}
}
?>
Whenever comment on any one of the issues, comment save successfully.
Comment saving code in given below:
$user = elgg_get_logged_in_user_entity();
$p_url = parse_url($_SERVER['HTTP_REFERER']);
if($p_url['path'] == '/issues/view' || $p_url['path'] == '/issues/respond')
$tracker_comment = TRUE;
else
$tracker_comment = FALSE;
if($tracker_comment)
{
action_gatekeeper();
// Get input
$entity_guid = (int) get_input('entity_guid');
$comment_text = get_input('generic_comment');
// Let's see if we can get an entity with the specified GUID
if ($entity = get_entity($entity_guid)) {
$comment = new ElggComment();
$comment->description = $comment_text;
$comment->owner_guid = $user->getGUID();
$comment->container_guid = $entity->getGUID();
$comment->access_id = $entity->access_id;
$guid = $comment->save();
// If posting the comment was successful, say so
if ($guid) {
system_message(elgg_echo("generic_comment:posted"));
} else {
register_error(elgg_echo("generic_comment:failure"));
}
} else {
register_error(elgg_echo("generic_comment:notfound"));
}
// Forward to the
forward($entity->getURL());
}
else
RETURN TRUE;
I am unable to retrieve the last comment username not updated in list of issues. I am using elgg_get_annotation() to retrieve the last comment details.
But not retrieving the details. Last comment code in given bellow.
if ($table_rows) {
foreach ( $table_rows as $entity ) {
if ($entity->unread == 1) {
$unread = "Yes";
} else {
$unread = "No";
}
if ($entity->assigned_to == 0) {
$assigned = "No";
} else {
$assigned = "Yes";
}
$last_options = array ();
$comments = elgg_get_annotations(array(
'annotation_names' => 'issue_tracker_changes',
'guid' => $entity->guid,
'limit' => 1,
'order_by' => 'n_table.id DESC',
));
foreach ( $comments as $comment ) {
$last_comment = get_entity ( $comment->owner_guid );
}
Comments are no longer annotations since Elgg 1.9 but entities. You are creating comment using ElggComment class that represents entity so you're using Elgg 1.9 or newer. You just need to use elgg_get_entities instead of elgg_get_annotations. Use type object and subtype comment.
i used an exsiting code from a tutorial and need to change it.
The original code doesnt use an array, but i need it.
In my index.php i am calling the function with a tag:
else if ($tag == 'getinvbykost') {
$kstalt = $_POST['kstalt'];
$get = $db->GetInvByKost($kstalt);
if ($get != false) {
// echo json with success = 1
$response["success"] = 1;
$response["ean"] = $get["ean"];
$response["name"] = $get["name"];
$response["betriebsdatenalt"] = $get["betriebsdatenalt"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "nicht erfolgreich";
echo json_encode($response);
}
}
the function GetInvByKost($kstalt); is defined in DB_Functions.php.
the part is:
public function GetInvByKost($kstalt) {
$result = mysql_query("SELECT ean, name, betriebsdatenalt FROM geraete WHERE kstalt='$kstalt' AND accepted='0'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
while ($result = mysql_fetch_assoc($result)){
}
return $result;
//echo $result[1];
}
else {
// user not found;
return false;
}
}
the problem is, the function GetInvByKost returns an array.
the part in the index.php
$response["success"] = 1;
$response["ean"] = $get["ean"];
$response["name"] = $get["name"];
$response["betriebsdatenalt"] = $get["betriebsdatenalt"];
isnt made for an array, only for a single line.
how do i can get the values in the array to build my output?
mysql_fetch_assoc($result) returns a flat array. This means you can't access returned array by a key. So $get["ean"] is wrong and $get[1] is correct. You can access result of mysql_fetch_assoc($result) only by index, not key. You have SELECT ean, name, betriebsdatenalt... in your query, so index of "ean" is equal to 0, "name" is equal to 1 and so on. Therefore, 3 parts of your code should be change in this way:
`$get["ean"]` => ` $get[0]`
`$get["name"]` => `$get[1]`
`$get["betriebsdatenalt"]` => `$get[2]`
Update:
So, the index.php file should be like this:
else if ($tag == 'getinvbykost') {
$response = array();
$kstalt = $_POST['kstalt'];
$get = $db->GetInvByKost($kstalt);
if ($get != false) {
// echo json with success = 1
$response["success"] = 1;
$response["ean"] = $get[0];
$response["name"] = $get[1];
$response["betriebsdatenalt"] = $get[2];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "nicht erfolgreich";
echo json_encode($response);
}
}