I'm trying to convert an excel scoring program and this one formula is driving me nuts. so this is the excel formula =IF(AD4<AE4,AE4-AD4,0) and I have been stumped for a little bit. I have looked at, and tried a few sample formulas for both PHP & MySQL, but I keep receiving syntax errors, unexpected if or else in the code.
So what the formula is checking to see if the elapsed time is under a set time, and if so, calculates the difference between the 2 fields and displays the outcome in time format hh:mm:ss.
This is the latest SQL query I tried:
Select *
if (`Under Time`<`Speed Fault`,0)
else { (`Time Elapsed`-`Speed Fault`)} As Under Time
from time_db
In sql , you can use case :
Select *,case when (UnderTime<SpeedFault)
then 0
else TimeElapsed - SpeedFault end As UnderTime
from time_db
SELECT *,
GREATEST(`Time Elapsed`-`Speed Fault`, 0) AS `Under Time`
FROM time_db;
Related
I have a PHP script that helps me to make some financial reports like capital, profits, total sold item, total item in store between 2 dates:
$result[] = 0;
$res[] = 0;
$fetchStat[]=0;
if(isset($_POST['generate_capital']))
{
$from_d = $_POST['from_d'];
$to_d = $_POST['to_d'];
$stat = "SELECT sum(sell_quantity*(sell_price-init_price)) AS 'rebeh', sum(init_price*(quantity-sell_quantity)) AS 'capital', sum(sell_price*sell_quantity) AS 'profits', sum(quantity) AS 'total_item', sum(sell_quantity) AS 'total_sell' FROM purchases WHERE date_now BETWEEN :d1 AND :d2";
$stmtStat = $conn->prepare($stat);
$stmtStat->bindValue(':d1', $from_d);
$stmtStat->bindValue(':d2', $to_d);
$execStat = $stmtStat->execute();
$fetchStat= $stmtStat->fetchAll();
}
Now, the same query in MySQL workbench will give me a specific result:
SELECT sum(sell_quantity*(sell_price-init_price)) AS 'rebeh',
sum(init_price*(quantity-sell_quantity)) AS 'capital', sum(sell_price*sell_quantity) AS 'profits',
sum(quantity) AS 'total_item',
sum(sell_quantity) AS 'total_sell'
FROM purchases WHERE date_now BETWEEN '2016-02-02' AND '2016-05-09'
The result is:
And the same query in the PHP script with the same date range will give me other values:
I've changed the Arabic keywords with English ones so you can see the difference.
Any help is appreciated.
EDIT: Adding var_dump result for 2 dates
As it stands, it appears that the most likely cause is that your date formats have the month and day in the wrong order, for the 2nd of February, that doesn't matter, but for the 9th of May, it would become the 5th of September.
Now, the reason that the data for the 9th of May isn't included when you run the query directly is because a date is actually midnight on that date, making it exclusive of that date when it comes at the end of a between.
It's possible there is something else, so if this doesn't work, try echoing out all your values at every point, until you know exactly what is being run, and it should become clear.
To clarify, when using '/' in a date, MySQL uses the following format:
'%d/%m/%Y'
Which would explain why it works if you enter a string into your text box.
I have a problem with executing ODBC query. I am trying to achieve something simple.
SELECT t.* FROM table t WHERE DateTime > '#2014-05-05 00:00:00#'
I have tried to execute with or without hashes (#) and quotes around the datetime, but no success with that. Also, instead of using >, < and other comparison operators I have tried to use BETWEEN.
In addition several formats "dd/mm/yyyy", "mm/dd/yyyy", "dd.mm.yyyy", etc. plus standard sql format (iso) were tested and the result is the same.
The approach looks like:
$sql = "SELECT t.* FROM table t WHERE DateTime > '#...#'";
$result = odbc_fetch_array(odbc_exec($odbc_connection, $sql));
After this execution I receive some 5-10 symbol binary error, but no error message (with odb_error and odbc_errormsg), in addition to the:
No tuples available at this result index
(The topic: ODBC error in PHP: “No tuples available at this result index” is not helping)
Could it be some ODBC issue (old version etc.) or we should cast another black magic through odbc_exec?
Maybe ODBC have trouble with reserved word datetime.
I don't know how to escape quotes in PHP, try
SELECT t.* FROM table t WHERE t."DateTime" > '20140505'";
You should use ODBC syntax for datetimes which is { ts '1998-05-02 01:23:56.123' }. You can omit the partial seconds. See here.
Have you tried using the TO_DATE() function? You can specify the format you are using.
SELECT t.* FROM table t WHERE DateTime > TO_DATE('2014-05-05 00:00:00','YYYY-MM-DD HH24:MI:SS')
im a newbie in PHP and im trying to solve this situation as much as i can but still don't get/know the right answer.
I have a table with 2 columns in database with time datatype
Lunch Break
00:01:00 00:00:30
Im trying to fetch the data and add the two times, but i always get the wrong value.
I have this code:
$time[$x] =$row['break'] + $row['lunch'];
$totalAux[$x] = $time[$x];
Output is : "00:00:00"
The i try this one:
$time[$x] =strtotime($row['break']) + strtotime($row['lunch']);
$totalAux[$x] = $time[$x];
And get an ouput of "00:00:00"
Then lastly tried this one:
$time[$x] =strtotime($row['break']) + strtotime($row['lunch']);
$totalAux[$x] = date('H:i:s', $time[$x]);
Output was: "09:33:14"
Please Help Guys .
You can use ADDTIME function from MySQL:
SELECT Lunch, Break, ADDTIME(Lunch, Break) FROM table_name;
sqlfiddle
Why don't you use the TIMEDIFF() and ADDTIME() functions which is to get the difference or to add times respectively in mysql so that it would be resolved there and php will just have to pick it up.
You need to use also TIME_FORMAT() in order to get the hours, minutes and seconds:
SELECT TIME_FORMAT(ADDTIME(lunch, breaks),'%H:%i:%s') as TimeTotal
FROM lunchbreaks;
SELECT TIME_FORMAT(TIMEDIFF(lunch, breaks),'%H:%i:%s') as TimeDifference
FROM lunchbreaks;
See the Demo
I am having a bit of trouble writing a mysqli query that queries between dates.
The column in my mysql database is a datetime column.
The query I have written in php looks like this
$sessions = mysqli_query($db,"SELECT s.idSession, s.idUser,
FROM rempad.Session AS s WHERE s.idUser = 12 AND s.start BETWEEN '2013-04-28' AND '2013-05-28'");
I have tried escaping the dates like \'2013-04-28\'
I have also tried casting as datetime like: DATETIME(s.start) BETWEEN DATETIME('2013-04-28') AND ...
But that doesn't work.
I have tested the SQL syntax in Mysql workbench so I know that the query returns values, but I can't seem to get it right in php.
Any ideas? I can't find any examples online.
Thanks in advance
L
I tried it and it worked as:
query($db,"SELECT s.idSession, s.idUser
FROM rempad.Session s WHERE s.idUser = 12 AND s.start BETWEEN '2013-04-28' AND '2013-05-28'");
Removed a comma and 'as' after table name.
I am unable to get the following code to work:
// dd/mm/yyyy for dates in SQL queries
$todayforw = date('d/m/Y');
$aweekago = date('d/m/Y', time() - 604800);
$week_e_check = mysql_query("SELECT * FROM earningslog WHERE user_id = '".$info['id']."' WHERE day >='".$aweekago."' AND day <'".$todayforw."'");
while ($week_e_info = mysql_fetch_array($week_e_check)) {
$week_e = $week_e + $week_e_info['user_earnings_amnt'];
}
The query returns zero rows, however, it should be returning data that matches the criteria.
Check your date format:
Should be:
YYYY-mm-dd HH:mm:ss
E.G.
2012-01-01 00:00:00 (January 1, 2012 at midnight local time)
Other date formats MAY work, but the best way to go about it is to use the same format that MySQL uses when they display the date, that's the only way I know that works every time.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Also your syntax is incorrect, you have two wheres, you should use AND.
Take a closer look at your query:
SELECT * FROM earningslog WHERE user_id = '".$info['id']."' WHERE day >='".$aweekago."' AND day <'".$todayforw."'"
Your Where clause appears twice.
Two things to think about - when you are selecting data, try and stay away from select * - you may get unexpected results of the table is ever modified.
Second, try and create the query as a parameterized query, instead of injecting the parameters directly into the where clause. By directly injecting your criteria the way you have, you are opening yourself up to a SQL injection attack.
By turning it into a parameterized query, you get the side benefit of being able to debug the queries directly against the database, reducing the amount of effort needed to copy it from a query tool into your code.
Your issue appears to be with your query syntax. You are stating WHERE twice, whereas you should only state it once and then use the AND or OR operators for further criteria. I would also suggest that you either move your statement into a variable or use die() to assist with debugging.
$week_e_check = mysql_query("SELECT * FROM earningslog WHERE user_id = '".$info['id']."' AND day >='".$aweekago."' AND day <'".$todayforw."'") or die(mysql_error());
In addition, you should not be using the mysql extension as use of this extension is discouraged. Instead, use the MySQLi or PDO_MySQL extension. Using one of these alternative extensions will help serve as the first step in preventing SQL injection. I would also suggest that you avoid using * and specify the column names to be returned instead.
Using PDO:
<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT * FROM earningslog WHERE user_id = ? AND day >= ? AND day < ?');
$sth->execute(array($info['id'], $aweekago, $todayforw));
$results = $sth->fetchAll();
?>
Try change the format of your strings from from d/m/Y to Y-m-d.
MySQL might be expecting it year first. In which case it could be doing the wrong thing with d/m/Y.
Also don't use the WHERE clause twice. Instead, combine conditions using AND, eg:
WHERE user_id = '".$info['id']."'
AND day >='".$aweekago."'
AND day <'".$todayforw."'
By the way, you can also try saying WHERE day BETWEEN ".$aweekago." AND ".$todayforw.", which might be easier syntax to read (as long as you change $todayforw to be the day before).