EDIT
Provided as requested is here how the Date column looks:
Jan 15, 2014
Jan 16, 2014
Aug 10, 2014
So what i am trying to achieve, is extract every row that contains Jan 2014, so i get every row for that month in that year.
Here is my PHP code that generates the query:
$monthYearString = $month . "%" . $year;
$query_current = "SELECT * FROM {$table_omsaetning} WHERE 'Date' LIKE " . "'{$monthYearString}'";
echo $query_current;
The echo gives me this query: SELECT * FROM table_name_here WHERE 'Date' LIKE 'Jan%2014'
Original question
I have a very weird issue here.
If i perform a search using phpAdmin provided by my hosting site, and search for rows that are like a certain date, it conjures up this SQL statement, and it finds 3 rows:
SELECT *
FROM `table_name`
WHERE `Date` LIKE 'Jan%2014'
BUT, when I try to do the same thing either using SQL statements in phpAdmin or my own code, it shows NOTHING? How come? It is 100% the same statement. Really can't understand how I can search using the built-in phpAdmin function, and then it generates that SQL statement, and then when I try to inject it myself, it just returns 0 rows instead of 3.
Hope it makes sense.
The difference between single quotes and backticks is important here. You have quoted your column name instead of using backticks. It should be:
SELECT * FROM table_name_here WHERE `Date` LIKE 'Jan%2014'
The backtick character (see the Date column in the query above) allows you to indicate it's a name rather than a string. In this case, if you didn't have these, you would get an error because Date is a reserved word. The backtick allows you to use reserved words for table and column names.
Where as the single quote means it's a string. In the case of your query, you were essentially searching for any records where the string 'Date' contains the string 'January 2014' which isn't possible and will always return zero results.
For more information, check out this SO question: When to use single quotes, double quotes, and backticks in MySQL
Your code should look like this:
$monthYearString = $month . "%" . $year;
$query_current = "SELECT * FROM {$table_omsaetning} WHERE `Date` LIKE '{$monthYearString}'";
echo $query_current;
Related
Trying to get a simply query going through and its not working - newbie here.
Other php files and queries do run well.
$sql = "select sum(rese_nshw) as noshows from tnht_eseo where edta_data = '19.10.01'" ;
$sumParse = oci_parse($conn, $sql);
oci_define_by_name($sumParse, "noshows", $total);
oci_execute($sumParse);
while(oci_fetch($sumParse)){
echo "noshows:". $total;
}
what's wrong ? just outputs blank.
Running the SQL query in Oracle directly, it outputs 6 as NOSHOWS for this query.
If EDTA_DATA is date (datatype), don't compare it to a string as '19.10.01' is a string. Oracle will implicitly try to convert it to appropriate date, but that doesn't have to work always. Besides 19.10.01 can be anything (2019 Oct 01, or 19 Oct 2001, or ...), depends on NLS settings.
Take control over it; see whether using date literal helps (it always has yyyy-mm-dd format):
where edta_data = date '2019-10-01'
Furthermore, if edta_data contains time component (hours, minutes, seconds), then the simplest option is to truncate it, e.g.
where trunc(edta_data) = date '2019-10-01'
but it'll prevent Oracle from using index on that column (if it exists). It can be fixed, no problem; but - first see whether anything of above helps.
You have to use Upper Case as defined here:
column_name The column name used in the query.
Use uppercase for Oracle's default, non-case sensitive column names.
Use the exact column name case for case-sensitive column names.
from: https://www.php.net/manual/en/function.oci-define-by-name.php
Then:
oci_define_by_name($sumParse, "NOSHOWS", $total);
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.
I don't know PHP at all, so I am struggling through this. I need to add an or section to a MySQL query, but the values I'm searching have double quotes. I need to figure out how to add them in PHP so they are passed in to MySQL. The current query looks like:
$query = 'SELECT * FROM ' .$tableName.' WHERE allowed_countries LIKE "%'.$regionId.'%" and skurules REGEXP "i:'.$secondlastdigit.';" and status = 1 ORDER BY id DESC LIMIT 1';
But I need to add an or statement to search for string values that looks like:
$query = 'SELECT * FROM ' .$tableName.' WHERE allowed_countries LIKE "%'.$regionId.'%" and skurules REGEXP "i:'.$secondlastdigit.';" or skurules REGEXP "s:1:'.$secondlastdigit.';" and status = 1 ORDER BY id DESC LIMIT 1';
with double quotes surrounding the second instance of '.$secondlastdigit.'; when passed into MySQL.
My JSON string I'm searching looks like this:
a:12:{i:1;s:2:"15";i:2;s:2:"10";i:3;s:2:"30";i:4;s:2:"50";i:5;s:3:"120";i:6;s:3:"240";i:7;s:3:"480";i:8;s:3:"960";i:9;s:4:"3786";s:1:"A";s:3:"100";s:1:"C";s:2:"60";s:1:"B";s:5:"18930";}
First of all: DON'T.
If you still want to, then...REALLY DO NOT.
Making SQL queries on serialized arrays is just hell. You should try to avoid it at all costs.
Either:
Convert the serialized column into a standard SQL table
or select the column into a PHP variable, unserialize it and search through it.
Example:
$properPhpArray = unserialize($sqlResult['column_name']);
Agreed, searching serialized string is not the best solution and what the developer did despite having a bottle_size table available. I needed a quick fix and no time/skill to rewrite a tax calculation magento extension so I used replace in the query to solve my problem for now.
Since "s:1:X" will always be just one alpha character after the 1 and will not match anything else. I change the query to:
$query = 'SELECT * FROM ' .$tableName.' WHERE allowed_countries LIKE "%'.$regionId.'%" and skurules REGEXP "i:'.$secondlastdigit.';" or replace(skurules,char(34),0) REGEXP "s:1:0'.$secondlastdigit.'0;" and status = 1 ORDER BY id DESC LIMIT 1';
Very hackish fix but gets me out of a bind for now..
Mark
I searched a lot and cannot find my answer. I'm trying to include 2 variable in my like statement to match a date that wasn't formatted correctly in a database I'm working on.
I need to:
Select count(*) as ABC
from database
where active like '1'
and agent = '$Employeestringid'
AND time LIKE '%$FilterMonth_%_$queryyear'"
The part that is currently not working is: '%$FilterMonth_%_$queryyear'
I need it to work and match a date formatted like: '9:10:31 PM Fri, May 20th 2016' by only capturing MONTH and YEAR.
When interpolating your variables in the string, PHP reads the _ as part of the variable name.
You need to use {} to prevent this behavior:
$query = "Select count(*) as ABC
from database
where active like '1'
and agent = '$Employeestringid'
AND time LIKE '%{$FilterMonth}_%_{$queryyear}'";
Remove the underscores
'%$FilterMonth%$queryyear'
I'm having trouble with the sql below. Basically I have rows that contains strings according to the format: 129&c=cars. I only want the digits part, e.g. 129. The sql query is:
$result = mysql_query("SELECT * FROM " . $db_table . " WHERE id LIKE '" . $id . "%'");
Why doesn't % work? I can't use %...% because it catches too much.
I would actually recommend using regular expressions fo the matching, but unfortunately, there is no way to capture the matching part with mysql. You will have to do the extraction in php. If you have an array containing all the results called $array:
$array = preg_replace('/^(\d+).*/', '$1', $array);
You can use the MySQL 'regexp' stuff in the WHERE clause to reduce the amount of data retrieved to just the rows you want. The basic for of your query would look like:
SELECT * FROM table WHERE field REGEXP '^$id&'
where $id is inserted by PHP and the data you want is always at the start of the field and followed by a &. If not, adjust the regex to suit, of course.
MySQL's regex engine can't do capturing, unfortunately, so you'll still have to do some parsing in PHP as soulmerge showed above, but with the 'where regexp' stuff in MySQL, you'll only have to deal with rows you know contain the data you want, not the entire table.
Using a query like this:
SELECT *
FROM mytable
WHERE id >= '0' COLLATE UTF8_BIN
AND id < ':' COLLATE UTF8_BIN
will return all strings that start with a digit and make your expression sargable, i. e. and index on id can be used.
This will make your query run faster.