I was trying to make a SQL statement in PHP, to convert a string into a time(6). But I have tried everything, for the last 12 hours, and have not made an inch of progress. I have tried these statements, all yield the same error.
UPDATE scheduling SET start='03:42PM' WHERE activityid=2;
UPDATE scheduling SET start=CONVERT(TIME(6),'03:42PM');
INSERT INTO scheduling(start) VALUES (start=CONVERT(TIME(6),'03:42PM'));
INSERT INTO scheduling(start) VALUES (start=CONVERT(TIME(6),'03:42PM'));
INSERT INTO scheduling(start) VALUES (start=CONVERT(TIME(6),'15:42'));
The error is
Syntax Error: unexpected '03:42PM'(single quoted text)"
I do not know how to fix this, the table exists, and i have sucesfully got other info using statements like SELECT activityid=2 FROM xxxxxx.scheudling
I guess I have two questions, either answer would work.
In my PHP document, how would I convert a string I get in from an Android Studio volley to a date. (I get the variable correctly, with $start=$_Post("start"), so that works, but I cant convert it into a time. I looked online, and tried everything that looked like it work work.
Conversion through SQL Code, I already tried CAST and CONVERT, neither works. My start column is type TIME(6).
I recommend testing expressions using a SELECT statement.
Firstly, the MySQL CONVERT function arguments are flipped around backwards.
The syntax is CONVERT(expr,type)
And type is supplied as a keyword, not a string literal. For example:
SELECT CONVERT('235',SIGNED)
To convert to a TIME datatype
SELECT CONVERT( '15:42' ,TIME(6)) // => 15:42:00.000000
The 'PM' part of the string literal will be ignored.
SELECT CONVERT( '03:42PM' ,TIME(6)) // => 03:42:00.000000
We can use the STR_TO_DATE function to return a TIME value from a string that contains the AM/PM indicator
SELECT STR_TO_DATE( '03:42PM' ,'%h:%i%p')
And there's no need to cast that to TIME(6), we can do this:
UPDATE scheduling
SET start = STR_TO_DATE( '03:42PM' ,'%h:%i%p')
WHERE activityid = 2
The STR_TO_DATE function is documented here:
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_str-to-date
The format patterns for STR_TO_DATE are documented here, under DATE_FORMAT:
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format
FOLLOWUP
Demonstration:
setup
USE test;
CREATE TABLE scheduling (activityid INT PRIMARY KEY, start TIME(6));
-- 0 row(s) affected
INSERT INTO scheduling (activityid) VALUES (2);
-- 1 row(s) affected
execute the update statement in the answer above
UPDATE scheduling SET start = STR_TO_DATE( '03:42PM' ,'%h:%i%p') WHERE activityid = 2 ;
-- 1 row(s) affected
results
SELECT * FROM scheduling WHERE activityid = 2;
-- activityid start
-- ---------- ---------------
-- 2 15:42:00.000000
SECOND FOLLOWUP
Use same sql_mode setting reported by OP:
SET ##sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' ;
Test:
SELECT STR_TO_DATE( '03:42PM' ,'%h:%i%p')
returns
(NULL)
But this more complicated expression:
SELECT TIME(STR_TO_DATE(CONCAT(CURRENT_DATE(),' ', '03:42PM' ),'%Y-%m-%d %h:%i%p'))
returns
15:42:00
The more complicated expression is a workaround to avoid behavior imposed by the STRICT_TRANS_TABLES and NO_ZERO_DATE in the sql_mode.
Related
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')
I have this table and the query I give returns wrong results, I am not sure where the problem is
the date comparisons
or
structure of the query
The query if not clear in the image is :
select * from transact where item_code='msft234' or item_code='hp550x' and transact_date>=STR_TO_DATE('06-07-2013','%d-%m-%Y') and transact_date<=STR_TO_DATE('12-07-2013','%d-%m-%Y')
Your query employs a wrong syntax:
WHERE item_code='msft234' OR item_code='hp550x'
AND transact_date>=STR_TO_DATE('06-07-2013','%d-%m-%Y')
AND transact_date<=STR_TO_DATE('12-07-2013','%d-%m-%Y')
since AND priority is higher, it means that it will be satisfied if either you get hp550x in that date interval, or you get msft234 regardless of the date.
You have to put the OR'ed item codes in parentheses: (item_code='..' OR item_code='..' OR ..), or use IN: e.g.
SELECT * FROM transact
WHERE item_code IN ('msft234', 'hp550x')
AND transact_date BETWEEN
STR_TO_DATE('06-07-2013','%d-%m-%Y')
AND
STR_TO_DATE('12-07-2013','%d-%m-%Y')
Also, depending on the type you select for the date fields, consider that for a date to be "less or equal than 12-07-2013", it has to be less or equal than 12-07-2013 at 00:00, i.e., almost the latest date that will match is 11-07-2013 at 23:59:59.
So "less or equal than 12-07" will actually never select any row from 12-07-2013 unless it happens to have been inserted exactly at midnight.
If you insert rows by only specifying the date, then it will very probably work - the rows will be input at midnight and matched at midnight. But if (some) rows are entered with the full datetime, e.g. because they're type datetime and updated with NOW(), then they will not match.
put the item conditions between ()
(ítem_code = 'msft234' OR ítem_code = 'hp550x') AND transact_date>=STR_TO_DATE('06-07-2013','%d-%m-%Y') and transact_date<=STR_TO_DATE('12-07-2013','%d-%m-%Y')
(ítem_code = 'msft234' OR ítem_code = 'hp550x') AND transact_date BETWEEN STR_TO_DATE('06-07-2013','%d-%m-%Y') and STR_TO_DATE('12-07-2013','%d-%m-%Y')
For security I will put with 2 ()
(ítem_code = 'msft234' OR ítem_code = 'hp550x') AND (transact_date BETWEEN STR_TO_DATE('06-07-2013','%d-%m-%Y') and STR_TO_DATE('12-07-2013','%d-%m-%Y'))
Hopefully I'm going about this the right way, if not I'm more than open to learning how this could be done better.
I need to pass a comma separated list of integers (always positive integers, no decimals) to a stored procedure. The stored procedure would then use the integers in an IN operator of the WHERE clause:
WHERE [PrimaryKey] IN (1,2,4,6,212);
The front-end is PHP and connection is made via ODBC, I've tried wrapping the parameter in single quotes and filtering them out in the stored procedure before the list gets to the query but that doesn't seem to work.
The error I'm getting is:
Conversion failed when converting the varchar value '1,2,4,6,212' to data type int.
I've never done this before and research so far has yielded no positive results.
Firstly, let's use a SQL Function to perform the split of the delimited data:
CREATE FUNCTION dbo.Split
(
#RowData nvarchar(2000),
#SplitOn nvarchar(5)
)
RETURNS #RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare #Cnt int
Set #Cnt = 1
While (Charindex(#SplitOn,#RowData)>0)
Begin
Insert Into #RtnValue (data)
Select
Data = ltrim(rtrim(Substring(#RowData,1,Charindex(#SplitOn,#RowData)-1)))
Set #RowData = Substring(#RowData,Charindex(#SplitOn,#RowData)+1,len(#RowData))
Set #Cnt = #Cnt + 1
End
Insert Into #RtnValue (data)
Select Data = ltrim(rtrim(#RowData))
Return
END
To use this, you would simply pass the function the delimited string as well as the delimiter, like this:
SELECT
*
FROM
TableName
WHERE
ColumnName IN (SELECT Data FROM dbo.Split(#DelimitedData, ','))
If you still have issues, due to the datatype, try:
SELECT
*
FROM
TableName
WHERE
ColumnName IN (SELECT CONVERT(int,Data) FROM dbo.Split(#DelimitedData, ','))
You can pass a comma separate list of values. However, you cannot use them as you like in an in statement. You can do something like this instead:
where ','+#List+',' like '%,'+PrimaryKey+',%'
That is, you like to see if the value is present. I'm using SQL Server syntax for concatenation because the question is tagged Microsoft.
There is an interesting bug -for me-.
Please follow the query i executed.
everything is normal.
mysql> select hex(current_user());
Result : 726F6F74406C6F63616C686F7374
everything is normal.
mysql> select substring(hex(current_user()),1,15);
Result : 726F6F74406C6F6
i added null string to second and third parameter of substring method. everything is normal.
mysql> select substring(hex(current_user()),''+1,''+15);
Result : 726F6F74406C6F6
when i add null string to firs parameter of substring.. there is return only 726.:S i was expecting same result of my latest query.
mysql> select substring(hex(current_user())+'',1,15);
Result : 726
mysql> select substring(hex(current_user())+'',2,15);
Result : 26
mysql> select substring(hex(current_user())+'',3,15);
Result : 6
mysql> select substring(hex(current_user())+'',4,15);
Result : NULL
I tested with Mysql 5.0.95 and 5.1.61 and same issue..! i tested same query with mid function instead of substring.. same again.
Any idea ? i was working on some kind of Web Application Firewall rule bypass and i realized to that bug.
It's converting HEX to integer (by taking characters from HEX until the first non-numerical character: 726) when you apply '+' operator. And empty string is converted (to integer: 0) also.
Example:
''+1 => 0+1=1
726F6F74406C6F63616C686F7374+'' => 726+0 = 726
concat() function should be used for concatenating strings.
You should be using concat if you want reliable results...
SELECT hex(current_user()),
hex(current_user())+'',
substring(hex(current_user())+'',1,15),
concat(hex(current_user()), ''),
substring(concat(hex(current_user()), ''),1,15);
I have the following piece of code, executing a pretty simple MySQL query:
$netnestquery = 'SELECT (`nested`+1) AS `nest` FROM `ipspace6` WHERE `id`<='.$adaddr.' AND `subnet`<='.$postmask.' AND `type`="net" AND `addr` NOT IN(SELECT `id` FROM `ipspace6` WHERE `addr`<'.$adaddr.' AND `type`="broadcast") ORDER BY `id`,`subnet` DESC LIMIT 1';
$netnestresults = mysql_query($netnestquery);
$netnestrow = mysql_fetch_array($netnestresults);
$nestlvl = $netnestrow['nest'];
echo '<br> NESTQ: '.$netnestquery;
Now, when I execute this in PHP, I get no results; an empty query. However, when I copy and paste the query echoed by my code (for debug purposes) into the mysql command line, I get a valid result:
mysql> SELECT (`nested` + 1) AS `nest` FROM `ipspace6` WHERE `id`<=50552019054038629283648959286463168512 AND `subnet`<=36 AND `type`='net' AND `addr` NOT IN (SELECT `id` FROM `ipspace6` WHERE `addr`<50552019054038629283648959286463168512 AND `type`='broadcast') ORDER BY `id`,`subnet` DESC LIMIT 1;
+------+
| nest |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
Can anybody tell me what I'm doing wrong? I can't put quotes around my variables, as then MySQL will try to evaluate the variable as a string, when it is, in fact, a very large decimal. I think I might just be making a stupid mistake somewhere, but I can't tell where.
Can you modify the line to say $netnestresults = mysql_query($netnestquery) or die(mysql_error());
It may be giving you an unknown error, such as a bad connection, missing DB, etc.
do an echo $netnestquery
before calling mysql_query
also add a die(mysql_error()) there.
WHERE `id`<=50552019054038629283648959286463168512
That's a pretty big number there.
PHP has issues with big numbers. The maximum size of an integer depends on how PHP was compiled, and if it's on a 64-bit system.
Have you checked that the variable containing that number hasn't been capped to a 32-bit or 64-bit integer? If it has been capped, you're going to need to take steps to make sure it's only being stored as a string in PHP. MySQL accepts strings that are entirely numeric as numbers without complaining.
(That being said, I'm not sure that MySQL can do anything with a number larger than 64-bits. The largest integer column is BIGINT, which is 64-bits. There's also NUMERIC, but it's treated as a floating point number, and that might not be what you want to do...)