Foreach with php and mysql - php

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.

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>";
?>

How to get top five calculations only to appear

I have a dog show website and attempting to display the top five kennel affixes with the most point gained over a year.
I have split up the point as seen in code and using an inner join on two tables. One being Results and the Other Dogs
I am having a problem showing the affix name with its points gained next to it. Also can not get the top five based on most points
Warning: A non-numeric value encountered in xxx on line 59
Notice: Undefined variable: total in xxx on line 68
This below is all that shows up and I think it is adding the if statements up.
3
6
Sorry not that great at and need some help.
<?php
$query = "SELECT result.placement, result.award, result.class_name, dogs.affix
FROM result
INNER JOIN dogs
ON result.resultID = dogs.dog_id
ORDER BY dogs.affix LIMIT 5";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
$affix = $row['affix'];
$placement = $row['placement'];
$award = $row['award'];
if($award === 'BCC'){
$points = $affix + 5;
}
if($award === 'DCC'){
$points = $affix + 5;
}
if($award === 'RBCC'){
$points = $affix + 4;
}
if($award === 'RDCC'){
$points = $affix + 4;
}
if($placement === '1st'){
$points = $affix + 3;
}
if($placement === '2nd'){
$points = $affix + 2;
}
if($placement === '3rd'){
$points = $affix + 1;
}
$total += $points;
echo "<li> {$affix} {$total}</li>";
}
?>
Three problems.
ORDER BY dogs.affix LIMIT 5 returns bottom 5 not top. It should be ORDER BY dogs.affix DESC LIMIT 5 to get the top.
affix returns either null or an emprty string and that's why you are getting the first error. Define this field as int not null default 0 in your database.
$total is not initialized. Assign it to 0 before the loop

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"];
}

How to limit MySQL query result to specific results?

I have a news table in MySQL Database I query the table and show the title of the news in one PHP pages but now the table getting bigger so I want to divide the results into pages I mean to show each 50 news title in one page (pagenation).
I use this query to bring the news :
SELECT news.*, categories.category, users.username
FROM news INNER JOIN
users on news.user_id = users.id INNER JOIN
categories on categories.id = news.category_id
order by news.timestamp DESC
limit $min,$max
and this is part of the PHP page (How I calculate the max and min)
$news_per_page = 50;
if(!empty($_GET['p_n']))
{
$p_n = $_GET['p_n'];
$max = $news_per_page*$p_n;
$min = ($max - $news_per_page);
}
else
{
$p_n = 1;
$max = 50;
$min = 0;
}
$news = all_news($max,$min);
The sql giving me wrong result when i pass the limits I do not know why. Is it wrong to specify the max and min of sql query by this way?? Should I correct something in this code?
The LIMIT clause, as explained in the docs, takes arguments offset and count. So if you want to get, for example, results from 201 to 250, you would use LIMIT 200, 50. Start by renaming your variables $min and $max to $offset and $count, and from there everything will fall into place.
Pseudocode:
offset = (requestedPageNumber - 1) * rowsPerPage;
count = rowsPerPage;
PHP Code:
(assuming page number is 0-based)
$rowsPerPage = 50;
$page = empty($_GET['p_n']) ? 0 : $_GET['p_n'];
$offset = $rowsPerPage * (int) $page;
$news = all_news($offset, $rowsPerPage);
If you've got problems handling pagination properly, I suggest you use some code that is working, for example a pagination class that takes three parameters:
The current page.
The total count.
The number of items per page.
And then that class will generate the LIMIT clause for you. Example:
$pageNumber = 1;
$totalCount = 17;
$perPage = 5;
$pagination = new LimitPagination($pageNumber, $totalCount, $perPage);
echo $pagination, "\n";
This would output
LIMIT 0, 5
because you'er on the first page. Such a class then could also filter out those problems you have here, for example setting to a negative page - just automatically. And also it can provide a lot of extra data, like the next and previous page, the current page, the number of total pages, if it is the first or the last page and what not:
$pagination->setPage(-2);
echo $pagination, "\n";
echo "Current: ", $pagination->getPage(),
"; Total: ", $pagination->getTotalPages(),
"; Previous: ", $pagination->getPreviousPage(),
"; Next: ", $pagination->getNextPage(),
"\n";
Output:
LIMIT 0, 5
Current: 1; Total: 4; Previous: 1; Next: 2
This is then easy to integrate with different code, including yours:
$pagination = new LimitPagination($_GET['p_n'], $totalCount, 50);
$limit = sprintf("%d, %d", $pagination->getOffset(), $pagination->getCount());
This should easily do it. Class is here as Gist: https://gist.github.com/4469154
You need to set start (this you can achieve by using current page and per page property) and the second information is how many results you want (again per page property).
LIMIT . ($p_n - 1) * $news_per_page .', ' . $news_per_page
So, in your script it will be:
if(!empty($_GET['p_n']))
{
// You need to protect your variables for SQL injection. For numbers (int) or integer() function it is enough.
$p_n = (int) $_GET['p_n'];
$max = (int) $news_per_page;
$min = (int) ($p_n - 1) * $news_per_page;
}
else
{
$p_n = 1;
$max = 50;
$min = 0;
}
The correct code is:
$news_per_page = 50;
if(!empty($_GET['p_n']))
{
$p_n = intval($_GET['p_n']);
$min = ($p_n-1) * $news_per_page;
$max = $news_per_page;
}
else
{
$p_n = 1;
$max = 50;
$min = 0;
}
$news = all_news($max,$min);
While $_GET['p_n'] is page_number you dont' need to make any multiplies

PHP / MySQL Specific Column Count

I have searched around on forums however all answers don't seem to work for my I am guessing it's more user error.
What I am trying to do:
Retrieve the data set from MySQL
Count the total number of rows
Work out specifically how many of them have the value "Y" in the metSLA column
Work out specifically how many of them have the value "N" in the metSLA column
Convert each of these metSLA values to a percentage
**The MySQL query works for sure and its stored in variable $result for reference.
*
//sla and total case count and percentages
$sla_met_rows = 0;
$sla_not_met_rows = 0;
$total_cases = mysql_num_rows($result);
while ($row = mysql_fetch_array($result))
{
if `metSLA` = "Y"
{
$sla_met_rows ++;
} else if `metSLA` = "N"
{
$sla_not_met_num_rows ++;
}
}
$met_percentage = 100 / $total_cases * $sla_met_rows;
$not_met_percentage = 100 / $total_cases * $sla_not_met_num_rows;
You can use a single MySQL query to get the percentage result:
SELECT COUNT( CASE WHEN `metSLA` = "Y" THEN 1 ELSE NULL END ) AS `Yes`,
COUNT( CASE WHEN `metSLA` = "N" THEN 1 ELSE NULL END ) AS `No`,
COUNT(1) AS `total`
FROM `TableName`
In your PHP, it'll be referenced as:
$result = mysql_query( <<The query above is here>> );
$row = mysql_fetch_array( $result );
$met_precentage = $row['Yes'] * 100 / $row['total'];
$not_met_precentage = $row['No'] * 100 / $row['total'];
Change
if `metSLA` = "Y"
{
$sla_met_rows ++;
} else if `metSLA` = "N"
{
$sla_not_met_num_rows ++;
}
To:
if ($row['metSLA'] == "Y")
{
$sla_met_rows ++;
}
else if ($row['metSLA'] == "N")
{
$sla_not_met_num_rows ++;
}
What you have has three problems:
You're missing the brackets around the conditions,
You're assigning (=) rather than comparing (==), and
You're running a shell command rather than getting the value from the database row.

Categories