how to calculate to get data using servqual formula in codeigniter - php

I have the data to be calculated using the servqual formula.
Servqual quality = perceptions - expectations / total users
First, I calculate all the active criteria
Second, I count all the users who answered the questionnaire
Third, I calculate all perceptions and expectations to get the sum of each.
Fourth I do multiplication for expectations. Because expectations are inputted by the admin. So expectations multiplied by the number of users.
Then I do the calculation with total perception minus the expectations divided by total user
Then servqual results, I update on the answer colomn in the result_jawab table.
Then I will display it according to the criteria and the results.
this my code. i dont know this code not work. please any body help me.
this image i attach for 2 table
function hasil_servqual(){
$jml_kriteria_aktif=$this->db->where('aktif','Y')->count_all_results("kriteria");
$kuisioner_aktif=$this->db->query("SELECT * FROM kuisioner WHERE aktif='Y'");
$aktif_kuisioner=$kuisioner_aktif->row();
$tenant=$this->db->query("SELECT id_tenant FROM hasil_kuisioner WHERE NOT id_tenant='0' AND id_kuisioner=$aktif_kuisioner->id_kuisioner");
$jumlah_tenant=$tenant->num_rows();
$persepsi= $this->db->query("SELECT SUM(jawaban) AS j_p FROM detail_jawaban WHERE id_kuisioner=$aktif_kuisioner->id_kuisioner");
$jumlah_persepsi= $persepsi->result_array('j_p');
$ekspektasi= $this->db->query("SELECT SUM(jawaban) AS j_e FROM detail_jawaban WHERE id_tenant='0' AND id_kuisioner=$aktif_kuisioner->id_kuisioner");
$jmlh_ekpektasi= $ekspektasi->result_array('j_e');
$jumlah_ekspektasi=("");
print_r($jumlah_ekspektasi);
$query=$this->db->query("SELECT * FROM kriteria WHERE aktif='Y' ORDER BY id_kriteria");
if ($query->num_rows()>0) {
$data=$query->result_array();
foreach ($data AS $value) {
$this->hasil.="<tr>";
$this->hasil.="<td>$value[id_kriteria]</td>";
$this->hasil.="<td>$value[kriteria]</td>";
$this->hasil.="</tr>";
}
}
}

Related

How to check whether a number lies between 2 values using Laravel query

I have to trigger a mail when student crosses several stages . I have two tables
studentreward_point_categories and
student_reward_points.
If any student reaches a stage then need to send a mail. How to get category from db .
Reward point Category table.
Student reward point table.
If for student_id = 19 have 345 points How to get his reward category. i have tried below code.
$total_point = StudentRewardPoint::where('student_id', $request->student_id)
->sum('points');
if(!empty($total_point)){
return $pointCategory = RewardPointCategory::where('from_value','>=', $total_point)
->where('to_value','<=',$total_point)
->where('status',1)
->first();
}
Using this query I'm not able to get user reward point category.
You are querying it totally wrong!! From my point of view swap your '<=' and '>='
return $pointCategory = RewardPointCategory::where('from_value','<=',$total_point)-
>where('to_value','>=',$total_point)->where('status',1)->first();

laravel slow query issue optimization

I want to optimize my query as it is taking long to run with current eloquents. I have two table, toys and product.
From each product one is reserved as sample of toy if not than it has to be updated as sample by the query so what i'm doing right now is below.
$toywithsample=product::select('toyid')->groupBy('toyid')->where('sample','yes')->get();
Above code is to get id of all the product with which have their one sample from in its product
$toywithoutsamples=toy::select('id')->whereNotIn('id',$toywithsample)->get();
Above code is to get id of all product which have no sample toy in
foreach($toywithoutsamples as $toywithoutsample){
$product=product::where('toyid',$toywithoutsample->id)
->where('sample','sale')->limit(1)
->update(['sample'=>'yes']);
}
Below is table structure
toy table
id,name,
product
id, toyid,sample
$toys_ids_with_sample = Product::where('sample', 'yes')->get()->pluck('toyId');
// get the products grouped by toyId.
$products = Product::whereNotIn('toyId', $toys_ids_with_sample)->where('sample', 'sale')->get()->groupBy('toyId');
// get the product ids whose sample field you want to change to
// yes.
$update_product_ids = [];
foreach($products as $toyId => $products){
// We will only pick the first one, as we have to change just 1.
array_push($update_product_ids, $products->first()->id);
}
Product::whereIn('id', $update_product_ids)->update(['sample' => 'yes']);
This reduces the total number of queries.

Ranking based on users placement instead of score

I have a issue that I cannot wrap my head around.
I am using the Laravel Framework.
I am trying to make a ranking table based on placement (Meaning the user does not have any SCORE, they just have placements)
How I want it to work is the following way:
User A = Placement: 1
User B = Placement: 10
User B wins over User A, then User B gets placed as number 1 and User A gets placed as number 2, and then I want it to update all the other users accordingly.
I can't seem to find a reliable way of doing this.
I don't think this is a Laravel challenge but an SQL one. And it may be simple to solve: basically, you will ask for the actual position of the defeated person, if the position is greater than the winner, you do nothing, otherwise you will assign the position of the loser to the new winner and update the rest of the table with a +1 in the position column.
In code it would be something like this:
$winner_player = User::where('id', userA->id)->first();
$loser_player = User::where('id', userB->id)->first();
if($winner_player->position < $loser_player->position) {
//Update the rest of the users.
//We add 2 because we need space for the new winner and for
//the loser that is still above of the rest of the players.
DB::table('users')
->where('position', '>', $loser_player->position)
->update(DB::raw('position+2'));
//Set the winner with the actual position of the loser.
$winner_player->position = $loser_player->position;
$winner_player->save();
//Set the looser with the new position (+1 of his actual).
$loser_player->position = $loser_player->position + 1;
$loser_player->save();
}
UPDATED LOGIC
As Classified pointed out, it moves the rows around but doesn't do it correctly, so I'm updating the logic to make it work as it is supposed to, and it will be a little simpler too.
$winner_player = User::where('id', userA->id)->first();
$loser_player = User::where('id', userB->id)->first();
if($winner_player->position < $loser_player->position) {
//Set the winner with the actual position of the loser.
$winner_player->position = $loser_player->position;
//Update the users between the swap. There is no need to update
//the whole table, we only update the records between the swap.
DB::table('users')
->where([['position', '<', $winner_player->position],
['position', '>=', $loser_player->position]])
->update(DB::raw('position+1'));
//Save the value of the winner AFTER updating the positions
//between winner and loser.
$winner_player->save();
}

Running a method for each field existing in the mysql table

Hello i have a small table in mysql which contains few fields with a description, name, price, id.
Foreach of the items inserted in this table i need to run a certain method in php to make some math based on the price field. How could i do this any ideas(in the future they will be more than two or three so it should be something a little bit dynamic if posible ) .
Update: this is the table.
-- Dumping structure for table print_finishes
DROP TABLE IF EXISTS `print_finishes`;
CREATE TABLE IF NOT EXISTS `print_finishes` (
`FinishesId` int(11) NOT NULL AUTO_INCREMENT,
`FinishesName` varchar(100) NOT NULL,
`FinishesPrice` varchar(100) NOT NULL,
PRIMARY KEY (`FinishesId`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
Update: Ok for those who didn't quite understand my question:
IN PHP:
I make a select based on the id's that are comming from a form.
Irun a foreach to loop data that is returned from mysql.
Now i need away to call up a method that is unique for each of the fields that i
return. ( this is the part that i don't know how to do it.
Example data returned
CutContour - 2euros
Laminate - 5euros
in that foreach i need to check somehow if i have a cutcontour option or something like that and run a method called CalculatePriceBasedOnCutContour ( which in my case the formula would be square meters multiplied by 2 euros now when it finds laminate option i need to run another method for example CalculatePricebasedOnLaminate (in this case i could use the same method that i called for cutcontour because the formula would be the same only the price changes.
/**
* Calculate Finishes for cut countour
* #param int $cutContourPrice [description]
* #param int $squareMeters [description]
*/
public function CalculateWithFinishes($cutContourPrice, $squareMeters ) {
$this->_cutContourPrice = $cutContourPrice * $squareMeters;
}
Third Update:
A simple way of doing would be like this:
if($printFinishes['name'] = 'CutContour) {
$this->CalculateWithFinishes($arg1, $arg2);
}
and this should be made dynamic because i can't know how they will be named in database
It was too long to post it as a comment.
A unique method based on the type selected. but i can have even three types selected from finishes tables. i can have laminate, cut contour, bonding on cmyk forex ( each of these finishes has a different price and some of them are calculated based on square meters ) to give a better understanding on what i'm doing it is about storing orders from a print shop in database and make price calculations and reports at the end of the month how much material was printed, how much was lost, how much material was lost during printing process and when it comes to order we have a big list of finishes based for each product. if you print on vinyl you could have even 5 types of finishes applied to it some of them calculated in square meters some of them not and i need to know what formulas should i apply and when based on what i select from a form.
So when i get the data from the form and get the required prices from the database i need a way to find out what finishes i applied to know what function i call to calculate the price.
This is how i calculate on daily bases:
Width * Height * finishes price * print square meter price * euro price * vat tax.
1.37 * 2 * 3 = 8.22 euros the cost of cut contour on the print
1.37 * 2 * 10 = 27.4 euros the cost of the printing process
35.62 * 4.5 * 1.24 = the total cost of the printing with finishes converted to my curency and added the vat tax
Translation width of the material multiplied by height ( everything is in meters ), that returns me the square meter then i apply a finishes price of 3 ( cut contour on the print ), then i apply the print price ( 10 euros / square meter ) then i convert the euro in my curency then i apply a vat tax on the final price.
Little example:
<?php
mysqli_connect($host, $user, $password);
//Connecting to the server
mysqli_select_db($yourdb);
//Select DB
$query=mysqli_query("SELECT * FROM print_finishes");
//Query
while($row=mysqli_fetch_assoc($query)){
//While PHP can get a new row from the output
echo $row['FinishesId'];
echo '<BR>';
echo $row['FinishesName'];
echo '<BR>';
echo $row['FinishesPrice'];
echo '<BR>';
echo '<BR>';
}
?>

ORM Mapping two tables with PHP

Current situation
I have two tables in my database, one for posts, and one for ratings. These are linked with a relation in the MySQL so that one post may have 0, 1 or multiple ratings, but one rating can only be applied to one post.
When I fetch a list of posts, I also want to get ratings, but without having to make a separate call to the database for each post in the foreach loop.
To do this I have attempted to use an SQL query to fetch all posts with a LEFT JOIN on ratings so that it will return a result like this:
statusId|statusBody|rating
-----------------------------
1, post1, 0
1, post1, 1
2, post2, 0
3, post3, 1
3, post3, 1
The SQL works fine, and I get the data I ask for.
Ideally what I am trying to achieve now is to turn this table into a collection of objects, with each object storing the post information as well as a value depending on it's total ratings.
After using PDO to return the data result, this is the code I am using to map the data:
Code Logic
The logic of my code goes like this:
Get all statuses joined with ratings table
Create empty output array
Loop through PDO result
{
Create loop specific temp array
Push first row of result into temp array
Remove row from PDO result
Loop through PDO result for objects with matching statusId
{
If row matches statusId, add to temp buffer and remove from PDO result
}
Take first row of buffer and create status object
Loop through objects in temp array to calculate ratings and add onto above status object
Clear temp buffer
Add status object to output array
}
return output array
Actual Code
try
{
$result = $pdo->query($sql);
//if($result == false) return false;
$statuses = $result->fetchAll(PDO::FETCH_CLASS, 'status');
}
catch (PDOException $e)
{
return FALSE;
}
if (!$result) {
return FALSE;
}
//create empty output array to be filled up
$status_output = array();
//loop through all status
foreach($statuses as $s1key => $s1value)
{
//initialise temporary array;
$status_temp_buffer = array();
//create temp array for storing status with same ID in and add first row
array_push($status_temp_buffer, $s1value);
//remove from primary array
unset($statuses[$s1key]);
//loop through array for matching entries
foreach($statuses as $s2key => $s2value)
{
//if statusId matches original, add to array;
if($s2value->statusId == $s1value->statusId)
{
//add status to temp array
array_push($status_temp_buffer, $s2value);
//remove from primary array
unset($statuses[$s2key]);
}
//stop foreach if statusId can no longer be found
break;
}
//create new status object from data;
$statObj = $status_temp_buffer[0];
//loop through temp array to get all ratings
foreach($status_temp_buffer as $sr)
{
//check if status has a rating
if($sr->rating != NULL)
{
//if rating is positive...
if($sr->rating == 1)
{
//add one point to positive ratings
$statObj->totalPositiveRatings++;
}
//regardless add one point to total ratings
$statObj->totalAllRatings++;
}
}
//clear temporary array
$status_temp_buffer = NULL;
//add object to output array
array_push($status_output, $statObj);
}
Problem
The problem I am coming up against with this code is that although the ratings are fine, and it correctly calculates the ratings total for each post, it still shows duplicates where a post has more than one rating.
Any help with this would be greatly appreciated,
Thanks
As i understood it, the goal is to get the total rating of each Post entry. Instead of manually looping over each and every rating, there are two other path you could take:
compute the total in the query:
SELECT SUM(rating) AS total , .. FROM Posts LEFT JOIN .... GROUP BY statusID
You will receive a list of Post entries, each already with total rating calculated. This is a very good solution if you have a lot of writes to to the Ratings table, and much less reads.
the other way is to break the table normalization, but to increase read performance. What you would have to do is to add another column in the Posts table: total_rating. And have an TRIGGER on INSERT in the Ratings table, which changes the Posts.total_rating accordingly.
This way has a benefit of simplifying the request of Posts. At the same time Ratings table can now be use to ensure that total_rating has been calculated correctly, or to recalculate the value, if there are some large changes in the ratings: like banning of user, which results in removing all ratings made by this user.

Categories