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>';
}
?>
Related
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.
In my app, the user can enter a number for pricing and based on the input, the database will return a plan with the same price. If there is no number/price corresponding to the user input, I would like the program to find the plan with the nearest value. How can I find the "nearest" value in a haystack?
Examples :
User inputs : $14, Returns the 15$ plan
User inputs : $20, Returns the 15$ plan
User inputs : 25$. Returns the 30$ plan
Etc...
This is what I have :
//Create pricing for each plan
$getplansql = "SELECT SUM(`Distributor Net Price`) AS dnetprice FROM `services` wspn
WHERE wspn.planName = '$planname_num[$pn]' AND wspn.planLevel = '$planlevels_num[$pl]'";
$resultplans = $conn->query($getplansql);
while($plan = mysqli_fetch_assoc($resultplans)) {// output data of each row
$inhousepricing = ($plan['dnetprice'] * 0.15) + ($plan['dnetprice']);
$finalpricing = round($inhousepricing);
if($planprice == $finalpricing) {//found matching row// there's a plan with that price
//put plan info in array
$planArray = array(
'planName' => $plan['name'],
'planPrice' => $finalpricing,
'planDescription' => $plan['description']
);
break;//stop statement and only get the first plan//row found
}else{//get the plan with the nearest value
//put plan info in array
}
Add 15% and find the closest price in the SQL query itself.
$getplansql = "name, description, dnetprice
FROM (
SELECT planName AS name, planDescription AS description, ROUND(SUM(`Distributor Net Price`) * 1.15) AS dnetprice
FROM `services` wspn
WHERE wspn.planName = '$planname_num[$pn]' AND wspn.planLevel = '$planlevels_num[$pl]'
) AS x
ORDER BY ABS(dnetprice - $planprice)
LIMIT 1";
$resultplans = $conn->query($getplansql);
$planArray = mysqli_fetch_assoc($resultplans);
This will just return the one row that you want, so you don't need a while loop.
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>";
}
}
}
I have a website that everything is working well except lowest price. I mean all prices will be changed based on selected currency but not lowest price.
Lowest Price is showing correctly just based on US dollar not other currencies, I mean If we will change currency to Euro, still lowest price is showing on US dollar which is default currency.
In my Sql Database I have a table pt_currencie and Column rate
and on my room page, lowest price is showing with following PHP code:
<?php echo $lowestPrice; ?>
and in the controller, the code is:
$this->data['lowestPrice'] = $this->hotels_lib->bestPrice($this->data['hotel']->id);
and here is setting for userdata and change currency
function changeCurrency($id){
$this->db->where('id',$id);
$rs = $this->db->get('pt_currencies')->result();
$this->session->set_userdata('currencycode', $rs[0]->code);
$this->session->set_userdata('currencysymbol', $rs[0]->symbol);
$this->session->set_userdata('currencyname', $rs[0]->name);
$this->session->set_userdata('currencyrate', $rs[0]->rate);
}
}
How can I show $lowestPrice based on selected currency (rate) ?
what formula should I add into above code that lowest price show based on selected currency?
Ok if I'm understanding your question correctly, you will have to take the currency rates out of the db into a php array and then determine the lowest price using php with something like this:
$query = "SELECT rate FROM pt_currencie";
$result = mysqli_query($db_conn, $query);
$rate_arr = mysqli_fetch_fields($result);
$currLowestPrice = $lowestPrice;
foreach ($rate_arr as $rate) {
$tmpLowestPrice = $lowestPrice * $rate;
if($currlowestPrice > $tmpLowestPrice)
$currLowestPrice = $tmpLowestPrice;
}
So this should atleast give you the lowest price in $currLowestPrice for adjusted to currency rates by the end of the for loop (the code above will probably have to be adjusted a bit for your program)
I am building a website for online exam , when user choose a particular exam
then subjects for is fetched from database.Then number of subjects is counted and then assigned to a variable $no_of_sub.
Each subject has sub categories stored in a variable $subject_cat[][].
$no_of_sub=7;//Here i assigned the no.of subject directly
$subject_cat= array ( array('Indian History','Indian national movement'),
array('Indian and World Geography',' Indian Geography',
'World Geography','Geography(jammu and kashmir)' ),
array('Indian Constitution','Indian Political History'),
array('Economic and Social Development',
'Sustainable Development',' Poverty',
' Inclusion', 'Demographics',
' Social Sector initiatives'),
array('Environmental Ecology',
'Bio-diversity and Climate Change','Physics ',
'Chemistry ','Biology','General Science'),
array('Defence Technology','Space Technology',
'Nuclear Technology','Biotechnology','Health',
'Other Technologies'),
array('Current events'),
array('General knowledge') );
//$subject_cat is a multi dimension array having sub categories for each subjects
for($i=0; $i<$no_of_sub; $i++)
//loop for subjects till no of subjects
{
for($j=0; $j<count($subject_cat[$i]); $j++)
//loop for each sub category within a subjects using multi dimensional array $subject_cat[subjects][sub_cat]
{
//Determine which subject to display the questions for
$query = "SELECT ques_id, q, op1, op2, op3, op4
FROM questions where cat='".$subject_cat[$i][$j]."' limit 3";
//for each subject category , it fetches data from MYSQL database Ex: where
cat="science"....
//
// other code goes here
//
My problem when running my code in local host , it does not fetching all category but only for one category
Where is the Indus Civilization city Lothal ? a) Gujarat b) Rajasthan c) Haryana d) Punjab
( ! ) SCREAM: Error suppression ignored for ( ! ) Fatal error: Maximum
execution time of 30 seconds exceeded in
C:\wamp\www\loginregister-master\testpage.php on line 68
My question is how to prevent this problem, i want to optimize my code because
each time when fetching data it took long time because my table has more than 3000 rows for each category.So the php execution time takes longer.
even i limited the query to 1 , the query has not any changes.
i just want to select 1 question from every category and process in shorter time.
Anyone who help me will be appreciated.
I found the solution
for loop requires more execution time and also the data cache capacity of server become increased due to data fetch in each cycle
hence now i use
separate function.It works perfectly now without any problem.