Need help pulling up this Mysql Query in php - php

I have a simple scenario but not getting it to work. I need to pull up a value for column 'fee' specified in Mysql Database according to two values.
I want to get the value for 'fee' if I specify an amount between columns 'from' and 'to'
Example: if amount is 95, the value for row 'fee' should be 0.99.
I tried to use traditional method previously like below but now I would like MYSQL query method. Please help.
if ($amount < 100) {
$fee = '0.99';
}
else if ($amount > 100 && $amount < 500) {
$fee = '1.99';
}
else if ($amount < 500 && $amount < 1000) {
$fee = '2.99';
}
else if ($amount < 1000 && $amount < 10000) {
$fee = '4.99';
}
else if ($amount > 10000) {
$fee = '9.99';
}
A Sample PHP Code:
<?
include "dbconnect.php";
$post_amount = $_POST["amount"];
$sql = "SELECT fee FROM fees WHERE from < '$post_amount' AND to > '$post_amount' LIMIT 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array( $result )) {
$fee = $row["fee"];
}
echo "Posted Amount is $post_amount and Fee is $fee";
?>

If I get your question, you need the SQL query.
You can use > and < signs:
"SELECT fee FROM tablename WHERE from < '$amount' AND to > '$amount' LIMIT 1"
Or you can use BETWEEN (How to search between columns in mysql):
"SELECT fee FROM tablename where '$amount' BETWEEN from AND to LIMIT 1"
Two more things:
You'll need to sanitize $amount variable before using it in the query
from and to are MySQL Reserve Words and should not be used as column names

MySQL has an awesome operator called BETWEEN:
"SELECT `fee` FROM `table` WHERE ".floatval($amount)." BETWEEN `from` AND `to`"

You just had problem in > and < all other things are fine in ur code there no need for other function to check it from database table.
I have checked it with this :
$amount = 250;
if ($amount < 100) {
$fee = '0.99';
} else if ($amount > 100 && $amount < 500) {
$fee = '1.99';
} else if ($amount > 500 && $amount < 1000) {
$fee = '2.99';
} else if ($amount > 1000 && $amount < 10000) {
$fee = '4.99';
} else if ($amount > 10000) {
$fee = '9.99';
}
echo $fee;
Its works fine.

Related

PHP Defining a variable based on calculations using another variable

I am trying to setup a subscription site that is based upon the number of people in a table.
Example: If there are less than 1000 people the cost is $Nil, if there are between 1,000 & 2,000 people, cost is $10, if there is between 2,000 & 3,000 people, cost is $20
I can output the $totalpeople no problems but it's where I want to get the $dkpsub that is causing the issues
I must be doing something wrong because I can't get it to work. Here is where I'm having troubles... Any help would be appreciated... Thanks Rog
<?php
$query = "SELECT count(id) as pcount FROM $people_table $wherestr";
$result = tng_query($query);
$row = tng_fetch_assoc( $result );
$totalpeople = $row['pcount'];
tng_free_result($result);
$dkpsub = if {$totalpeople < 1000,'Nil'};
echo "<ul><li><strong>USD$$dkpsub per annum</strong></br></li></ul>";
?>
Update: S. Imp has more detailed answer above
You should separate definition and assignment. PHP manual
<?php
$query = "SELECT count(id) as pcount FROM $people_table $wherestr";
$result = tng_query($query);
$row = tng_fetch_assoc( $result );
$totalpeople = $row['pcount'];
tng_free_result($result);
$dkpsub = 0;
if ($totalpeople < 1000) { $dkpsub ='Nil'; }
elseif ($totalpeople < 2000) { $dkpsub ='10'; }
else { $dkpsub ='20'; }
echo "<ul><li><strong>USD$$dkpsub per annum</strong></br></li></ul>";
?>
First, you should always check the result of a query for errors. If a query fails, you can get yourself into trouble if your code assumes the query always works. I'm not familiar with the tng_query function, but you might want to check into what it does if the query fails.
Secondly, this doesn't look like valid PHP, so I'm guessing you are getting a syntax error:
$dkpsub = if {$totalpeople < 1000,'Nil'};
In your case, it looks like you'll want an if/elseif/else statement -- but I wonder what will happen if $totalpeople is greater than 3000? Anyways, something like this might work up to that point:
//If there are less than 1000 people the cost is $Nil
if ($totalpeople < 1000) {
// are you sure you want to set it to $Nil?>
$cost = $Nil; // do you maybe mean NULL? or 'Nil'? or perhaps 0?
} elseif ($totalpeople >= 1000 && $totalpeople < 2000) {
// if there are between 1,000 & 2,000 people, cost is $10
$cost = 10;
} elseif ($totalpeople >= 2000 && $totalpeople < 3000){
// if there is between 2,000 & 3,000 people, cost is $20
$cost = 20;
} else {
throw new Exception("unexpected total people encountered");
}
So do think this may work?
<?php
$query = "SELECT count(id) as pcount FROM $people_table $wherestr";
$result = tng_query($query);
$row = tng_fetch_assoc( $result );
$totalpeople = $row['pcount'];
tng_free_result($result);
if ($totalpeople < 1000) {
$dkpsub = 'Nil';
} elseif ($totalpeople >= 1000 && $totalpeople < 2000) {
$dkpsub = 10;
} elseif ($totalpeople >= 2000 && $totalpeople < 3000){
$dkpsub = 15;
} else ($totalpeople > 3000){
$dkpsub = 20;
}
echo "<ul><li><strong>USD$$dkpsub per annum</strong></br></li></ul>";
?>

Filter negative and positive values out of one variable in PHP

I have a variable in PHP where values from a database are inserted. It’s about money. I need to summarize all negative and positives values separately.
Example:
February, I have:
+ 10
− 10
+100
− 50
− 15
+ 70
+ 80
—
Credits added: 260 Euro
Credits paid: −75 Euro
The variable is named $amound in my PHP file. I really have no clue how to do that.
In Excel, this would be as follows: =SUMMEWENN(E1:E48;"<0")
But here I only have a variable, not fields.
Heres some Code:
$reportdata["tableheadings"] = array("Transaktions-ID","Kunde","Datum","Beschreibung","Betrag");
if ($startdate && $enddate) {
$query = "SELECT tblcredit.*,tblclients.firstname,tblclients.lastname FROM tblcredit INNER JOIN tblclients ON tblclients.id=tblcredit.clientid WHERE tblcredit.date BETWEEN '".db_make_safe_human_date($startdate)."' AND '".db_make_safe_human_date($enddate)."'";
$result = full_query($query);
while ($data = mysql_fetch_array($result)) {
$id = $data["id"];
$userid = $data["clientid"];
$clientname = $data["firstname"]." ".$data["lastname"];
$date = fromMySQLDate($data["date"]);
$description = $data["description"];
$amount = $data["amount"];
$currency = getCurrency($userid);
$amount = formatCurrency($amount);
$overallamount += $amount;
// $overallamountout -= $amount;
// $overallamountin += $overallamount > 0;
$reportdata["tablevalues"][] = array($id,''.$clientname.'',$date,nl2br($description),$amount);
}
Indeed, this is very simple (I assume that all of your variables are strings, e.g. coming from a text file, but even if not it will work):
$var1 = '+80';
$var2 = '-30';
$result = (int)$var1 + (int)$var2;
var_dump($result);
Will result in: "int(50)" => Working fine.
You can do it in the DB
SELECT SUM(numbers) AS sum1 FROM pepa WHERE numbers > 0;
SELECT SUM(numbers) AS sum2 FROM pepa WHERE numbers < 0;
Okay,
its done.
Heres the Code which was used:
$summeGesamt = 0;
$summeEingezahlt = 0;
$summeAusgezahlt = 0;
$summeGesamt = $summeGesamt + $data["amount"];
if ( $data["amount"] >= 0) {
$summeEingezahlt += $data["amount"];
} else {
$summeAusgezahlt += $data["amount"];
}

If-else statement to count some variable

I need some help to solved this algorithm problem with How a Person is popular in his city.
My situation
How the algorithm should work like
If a person "mark" has 500 friends in his city out of 500,000.
(500/500,000)*50,000 = 5
So 5 in 50,000 people Know him right.
But When friends count increase the 50,000 should decrease
If "sam" has 1000 friends then
(1000/500,000)*25000 = 5
So 5 in 25000 people know his name
Yes we could implement this in if/else condition
If so then i have to write 500 lines of code.
Is there another way to do this in PHP?
<?php
$totalfriends = 100;
$totali = 5000000;
$name = "Sam";
if ($totalfriends >= 100 && $totalfriends <= 499 ) {
$r = ($totalfriends/$totali)*50000;
echo round($r),' ',"in 50K People on City regonize this Profile";
}else if ($totalfriends >= 500 && $totalfriends <= 999) {
$r = ($totalfriends/$totali)*25000;
echo round($r),' ',"in 25K People on City know".$name;
}else{
echo "";
}
?>
is this what you are looking for?
foreach([100, 500, 543, 1000, 5000, 51000, 500000] as $my_friends)
echo '5 in '. getScoreOf($my_friends) . "<br>";
function getScoreOf($my_friends){
$of = 5;
$total = 5e5; //that's 500,000 ;)
$step = 100; //minimum step, so output is not "4604" but "4600"
$out_of = $total / $my_friends * $of;
return $out_of > $step? round($out_of / $step) * $step: round($out_of);
}
run it in sandbox
edit: solution merged with original code
<?php
$of = 5;
$totalfriends = 100;
$name = "Sam";
echo $of ." in ". getScoreOf($of, $totalfriends) ." people in city know ". $name;
function getScoreOf($of, $my_friends){
$total = 5e6; //that's 5,000,000 ;)
$step = 100; //minimum step, so output is not "4604" but "4600"
$out_of = $total / $my_friends * $of;
return $out_of > $step? round($out_of / $step) * $step: round($out_of);
}

Foreach with php and mysql

I have the following code which provides the profit results of my rows depending on what Resultat_ID is set to.
$result = mysql_query('SELECT Indsats, Odds, Resultat_ID, Kamp FROM spil');
$row = mysql_fetch_assoc($result);
echo " Gevinster: ";
$Indsats = $row['Indsats'];
$Odds = str_replace(",", ".", $row['Odds']);
$sum = 0;
while($row = mysql_fetch_array( $result ))
{
$Indsats = $row['Indsats'];
$Odds = str_replace(",", ".", $row['Odds']);
if ($row['Resultat_ID'] == 1) //Win
{
$sum += $Indsats * ($Odds-1);
}
elseif ($row['Resultat_ID'] == 2) //Loss
{
$sum += $Indsats * -1;
}
elseif ($row['Resultat_ID'] == 3) //HalfWin
{
$sum += $Indsats * ($Odds-1) * 0.5;
}
elseif ($row['Resultat_ID'] == 4) //HalfLoose
{
$sum += $Indsats * -0.5;
}
}
echo $sum;
I also have a column called Tipper_ID which contains a number for each tipper and a table that contains Tipper_ID and Tipper_Name.
Besides the total profit results above, I want to get the profit results for each tipper, so basically run the above section for "all" and for each Tipper_Name in the Tipper-table and get the profit results for each part.
How do I do that ?
Danish/English Translations:
Gevinster = Gains<br>
Indsats = Effort<br>
Odds = Odds<br>
Resultat = Results<br>
Kamp = Match/Game<br>
Spil = Games<br>
Tipper = Tips
You have 2 options:
Inside your while, perform another query for each result (depending on the number of results, performance can be not that good)
Create a VIEW with the results grouped by Tipper_Name (or whatever you need) and change your query adding an INNER JOIN using the VIEW you just created. Even if this solution is a little bit more complex, it's faster!
This actually looks like a classic SQL problem:
SELECT t.TIPPER_ID, t.TIPPER_NAME,
SUM(CASE(s.Resultat_ID WHEN 1 THEN Indsats*(Odds-1) ELSE 0 END)) AS Win,
SUM(CASE(s.Resultat_ID WHEN 2 THEN Indsats*(-1) ELSE 0 END)) AS Loss,
SUM(CASE(s.Resultat_ID WHEN 3 THEN Indsats*(Odds-1)*(0.5) ELSE 0 END)) AS HalfWin,
SUM(CASE(s.Resultat_ID WHEN 4 THEN Indsats*(-0.5) ELSE 0 END)) AS HalfLoss
FROM spil AS s
LEFT JOIN TIPPERS AS t ON t.TIPPER_ID=s.TIPPER_ID
GROUP BY s.TIPPER_ID
For the total you should simply add those in the php.

Calculate percentage of up votes

I have searched this site and Google and even though the idea is pretty simple I can't figure it out.
I need to (like seen on YouTube) calculate the % of up-votes based on the amount up-votes and down-votes.
I have two vars, $upvotes and $downvotes now i need to calculate $ratio
For example
$upvotes = 3;
$downvotes = 1;
The ratio here needs to be 75 (%)
If you have
$upvotes = 0;
$downvotes = 100;
It needs to be 0 (%)
How do I calculate the percentage (in PHP)?
Simply
if(($upvotes+$downvotes) != 0)
$percentage = (float)($upvotes/($upvotes+$downvotes))*100;
else
$percentage = 0;
Simple maths!
$ratio = $upvotes / ($upvotes + $downvotes) * 100;
if($downvotes > 0 || $upvotes >0) {
$percentage = ($upvotes / ($upvotes+$downvotes));
}
elseif($upvotes > 0 && downvotes == 0) {
$percentage = 1;
}
$percentage = round(100*$percentage);
$percentage .= "%"; // if you want to add %
I tested it and it works.
$percent = ( $upvotes / ( $upvotes + $downvotes ) ) * 100;
$percentage = (float) round((100 /($upvotes + $downvotes)) * $upvotes, 2);
I would do a round on it aswell, this will round the result to the closest integer.
eg. 75.5% = 76%;
$ratio = round((($upvotes/($upvotes+$downvotes))*100), 0, PHP_ROUND_HALF_UP).'%';

Categories