How to have a sum() with a where clause - php

I currently have:
// connect for other mins
$sql = "SELECT sum(mins) FROM completed_activity WHERE member_id = '$_SESSION[SESS_MEMBER_ID]' AND exercise != 'Personal Training' AND date >= '$mon'";
But, when the date is not within the where clause, nothing is shown. I'm not even getting my 'else' statement.
Any ideas?
MAYBE SOLVED
I may have got the correct way of doing it with:
$sql = "SELECT sum(CASE WHEN member_id = '$_SESSION[SESS_MEMBER_ID]' AND exercise != 'Personal Training' AND date >= '$mon' THEN mins ELSE 0 END) AS mins FROM completed_activity";
Can anyone confirm if this looks right?

When using SUM, there are at least one result returned. The result of SUM may be 0 or more.
That's why your code is not working correctly.
Try the following code:
// connect for other mins
$sql = "SELECT sum(mins) AS mins_sum FROM completed_activity WHERE member_id = '$_SESSION[SESS_MEMBER_ID]' AND exercise != 'Personal Training' AND date >= '$mon'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$mins = $row["mins_sum"];
if ($mins > 0) {
echo "yes";
} else {
echo "no";
}
}

I dont know php code, But When No condition matched sql query will return 0.
Means There will be atleast 1 record. So your if condition will always true.
Improve condition to check for value like
if ($result['sum'] > 0) { //Check for syntax
while($row = $result->fetch_assoc()) {
$mins = $row["mins"];
echo "yes";
}
} else {
$mins = 0;
echo "no";
}

Related

progressive string mixed with int generation

I'm encountering a problem with the generation of a number which increases everytime an operation is called.
When the value arrive to 10, i can't print 11 and so on...
$this->sql = "SELECT codice FROM accettazione ORDER BY id DESC LIMIT 1";
if ($result = $this->hookUp->query($this->sql)) {
if ($result->num_rows > 0) {
while ($rw = mysqli_fetch_array($result, MYSQLI_BOTH)) {
(int)$codice = substr($rw['codice'], -1);
if ($codice < 9) {
$rw['codice'] = date("Y") . ".0000";
} else /*if ($codice == 9 || $codice < 99)*/ {
$rw['codice'] = date("Y") . ".000";
}
echo $rw['codice'] . ++$codice;
}
} else {
echo date("Y") . ".00001";
}
} else if ($this->hookUp->query($this->sql) === false) {
echo "fail";
}
}
The goal is to print 00001 when the value is lower than 10, ++00010 when lower than 100, ++00100 when lower than 1000, and so on...
When the code is 00010, at 00011, the value goes back to 00001 (if ($result->num_rows > 0) isn't satisfied anymore).
In the mySQL table, $rw["codice"] is a VARCHAR.
Why?
I guess you want your values displayed with leading zeros. That is:
1 displayed as 00001
9 displayed as 00009
11 displayed as 00011
1234 displayed as 01234
This is a requirement as old as the IBM 029 keypunch machine. (If I guess incorrectly, please edit your question.)
It's easy in php using sprintf.
$string_codice = sprintf('%05d', $codice);
EDIT
I think you're doing this the hard way. It looks like you want a string that reads 2015.00001 or 2015.09876 or suchlike. But I'm not confident guessing your requirements from your code. For one thing, I don't know what the values in your codice column in your database table look like.
Maybe you could try something like this.
/* assume the counter starts at zero */
$codice = 0;
if ($result->num_rows > 0) {
/* fetch the counter value from the table if nay. */
while ($rw = mysqli_fetch_array($result, MYSQLI_BOTH)) {
(int)$codice = $rw['codice']; /* no substr */
}
}
/* add one to the value and format it YYYY.000nn */
$codice++;
$stringval = date("Y") . "." . sprintf('%05d', $codice);
echo $stringval;

PHP if with an array SQL

I've got a problem here
$resultContLog = mysql_query("SELECT count(*) FROM dailyLogs WHERE data_log > NOW() - INTERVAL 30 MINUTE and server_id_log=".$Fid.";");
$Adata = mysql_fetch_assoc($resultContLog);
if ($Adata > 0)
{
echo 'OK';
}
else
{
echo 'NOT OK';
}
My php function returns the number of rows; i did this to include new logs if it happen later than 10 minutes. The if ($Adata > 0) statement doesn't work properly. Can you guys help me, please?
to check this , use this
Your need to check for count column you are getting from query if it is grater than zero, here it is used as alias of "total"
$resultContLog=mysql_query("SELECT count(*) as total FROM dailyLogs WHERE data_log > NOW() - INTERVAL 30 MINUTE and server_id_log=".$Fid.";");
$Adata=mysql_fetch_assoc($resultContLog);
if($Adata['total'])
{
echo 'OK';
}
else
{
echo 'NOT OK';
}
You fetch the DB result as an array, thus you can count it:
if (count($Adata)) {
echo 'ok';
} else {
echo 'not ok';
}
Your query is a bit of a mess though. Maybe you could place some logic outside of the SQL.
The date function of PHP is flexible and works good with MySql.
// instead of NOW() - INTERVAL 30 MINUTE
date("Y-m-d H:i:s", time() - 60*30);
Regards
*) edit: What #esqew said

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.

Compare date/time from form to dates/times in database

UPDATE
I edited my code, so now the time is checked correctly:
while($row = mysqli_fetch_array($result)){
$rid = $row['roomid'];
$begin = $row['start'];
$bval = strtotime($begin);
$einde = $row['end'];
$eval = strtotime($einde);
$staco = strtotime($start); //starttime posted from form
$endco = strtotime($end); //stoptime posted from form
$abegin = array(sta => $bval);
$aeinde = array(sto => $eval);
// print_r($abegin);
// print_r($aeinde);
foreach($aeinde as $sto) {
if($staco <= $sto) {$checksto = 1;}
else {$checksto = 0;}
}
foreach($abegin as $sta) {
if($endco <= $sta) {$checksta = 1;}
else {$checksta = 0;}
}
if($checksta == $checksto) {$ok = 1;} else {$ok = 0;}
print_r($ok);
}
}
}
So now: how do I check if $ok contains one or more 0's (don't book the room) or all 1's (book the room).
$roomstate = array(state => $ok) results in more than one array:
Array ( [state] => 0 ) Array ( [state] => 1 ) Array ( [state] => 1 )
I'm doing something wrong, because I think it should be possible to get all the different $ok's in one array and then
if(in_array(0,$roomstate)) { echo "Do not book";} else {$bookitsql = "INSERT INTO reservations ...";}
UPDATE: There is a flaw in my original logic to check availabilty with the rooms that needs to be solved first: now the rooms are not checked correct, so it is impossible to answer this question since the correct data is not displayed. My apologies.
For a system that books rooms I need to check with a new booking if the room is already is booked at the moment. The booking works with a form, and then it compares the results from the form with the content in the database for that room on that date.
while($row = mysqli_fetch_array($result)){
$rid = $row['roomid'];
$begin = $row['start'];
$bval = strtotime($begin);
$staco = strtotime($start);
$einde = $row['end'];
$eval = strtotime($einde);
$endco = strtotime($end);
$abegin = array(sta => $bval);
$aeinde = array(sto => $eval);
foreach($abegin as $sta) {
if($staco $checksta,checkstop => $checksto);
print_r($meh);
}
BetterQuestion:
Now I get `$staco` and `$endco`, which are the start and stoptime from the form.
I also get `$sta` and `$sto`, which are multiple start and stoptimes from the database.
Example:
existing reservations:
sta sto
1: 0800 0959
2: 1130 1259
So now when I get `$staco = 1000` and `$endco = 1114` it doesn't check right.
It only works if the new reservation is later than all the other reservations in the database. How can I solve this?
Your Target Pseudocode shows that you want it all be 0. $meh is an Array.
So what you do now is using a foreach on $meh and then Mark it as Occupied as soon as 1 appears. if this doesnt happen, you can assume that $meh is free, and do you Booking.
$roomState = 0;
foreach($meh as $mehValue){
if($mehValue == 1){
$roomState = 1;
}
}
if($roomState == 1){
print_r("room is occupied");
} else {
//insert stuff
}
Took a different approach, by checking date in my sql-statement.
So, the form posts $start and $end (when the users wants to make a reservation).
Now my code looks like this (and it looks ok, I think):
//form and other errormessages like username==0; $start>$end etcetera
else {
$reservationsql = "SELECT * FROM reservations WHERE roomid = '$roomid' AND ('$start' between start AND end) OR ('$end' between start AND end) OR ('$start' >= start AND '$end' <= end) OR ('$start' <= start AND '$end' >= end)";
$result = mysqli_query($link,$reservationsql) or die(mysql_error());
$num = mysqli_num_rows($result);
if($num>0) {"Error: room already booked at that moment";}
else {//$query = "INSERT INTO ..."}
}
}mysqli_close();
Thanks for all the help here and to think along with me.

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