MySQL query String contains
Hello, I am trying to make an mysql query that looks for a column value that contains a string from a master string I set. So if my master string is '1234567', I would like it to return any results with column values that have '1','2', etc... The above link was as close as to what I can find but I need it comparing in the opposite direction.
eg.:
WHERE '%{$needle}%' LIKE `column`
You are a little vague about where the various values are being stored (your text uses terms like "master string" but the sample code uses different names).
You can do what you want using regexp. Here is an example:
select 'abcd6efg' regexp concat('.*[', '1234567', '].*')
To be honest, regex is different from like in one important respect. regex returns true if any part of the left string matches, whereas for like the entire string has to match. So, the following also works:
select 'abcd6efg' regexp concat('[', '1234567', ']')
I like to put the explicit wildcards in to avoid mistakes when switching between the two.
You can look up the documentation for regular expressions here.
How about
WHERE ? LIKE CONCAT('%', `column`, '%')
where ? is a placeholder having a bound parameter with your master value (1234567) because you are using the PDO or MySQLi extension, right?
You're most certainly not using the deprecated MySQL extension, surely.
Related
I am trying to get some data, and in the table, there is a field named "sysload". However, it is a var(string) type. The data in it is like "0.0, 0.2, 0.5",three numbers split by comma. However, in the sql, I only need the last number(in this example:0.5) to compare in "where". So how can I use it ? My code:
$termquery=mysql_query("SELECT a.terminal FROM terminal_server_log a
inner join
(
SELECT terminal, MAX(timestamp) timestamp
FROM terminal_server_log
group by terminal
) b on (b.terminal=a.terminal and a.timestamp=b.timestamp)
WHERE explode(',', sysload)[2]>$number");
The last line is the most important one, i want to compare with '$number', but it seems i cannot use 'explode'. Thanks
You can probably use regular expressions to match the last element of your sysload column: https://dev.mysql.com/doc/refman/8.0/en/regexp.html#function_regexp-instr
Look also at CAST() function, as the extracted substring should be converted to a numeric value to allow comparison with a number.
PHP functions will not work inside SQL queries.
You can remove this filter from your query and filter at the php side, or you can make a custom explode function using some mysql string functions.
In this link has an example: (I didn't check if it's working)
Equivalent of explode() to work with strings in MySQL
I have a database where I store a code which is an implode("|", $array) of various codes. So the results will be something like:
100|5100|510
100|5200|510
410|5200|520
100|790|5100|320
I want to write a regular expression to search mySQL for matches from PHP ... I might have something like 100|*|510 to show me both 100|5100|510 and 100|5200|510. This RegEx works in PHP:
/100\|(?:.*)\|510/
But it does not work in mySQL. I found answers that ?: does not work, so if I remove that and use
/100\|.*\|510/
i.e. Query is:
SELECT * FROM tra_amounts WHERE coa_codes REGEXP "/100\|.*\|510/"
It shows all results from the table.
How do I write a RegEx to match some parts of the code, while leaving other parts of the code as a wildcard?
Thanks!
Have you heard of MySQL's LIKE operator? Something like this might be what you have in mind:
SELECT *
FROM yourTable
WHERE someCol LIKE '100|%|510;
Assuming that someCol had 100|5100|510 and 100|5200|510 as data, this query would return both of these records.
Use RLIKE instead of LIKE or =.
I tried to get results from my database using SQL but my results do not agree with what i am using as input. I always gets results from those who contains both integers and characters. For example, if i search for "liu" i get a result of "2LK020". I neither cant search with integers and get a correct result... I use:
$result = queryDatabase(
"SELECT course_tag, course_name FROM course WHERE course_tag OR course_name LIKE ?",
array(1 => '%' .$parameters[0]. '%')
is there a problem using "%"? or why do i get this weird answers?
Read this: http://dev.mysql.com/doc/refman/5.7/en/operator-precedence.html
You're doing the equivalent of
WHERE course_tag OR (course_name LIKE ?)
which comes to
WHERE true/false OR true/false
As long as course_tag isn't an empty string or a null or other "falsey" value, it'll pretty much always evaluate to a true value, and make the entire WHERE clause evaluate to true.
You can't test multiple fields against a single LIKE value. That simply doesn't work. You need to test each one individually:
WHERE (course_tag LIKE ?) OR (course_name LIKE ?)
However, since you're doing a %...% double-wild card search, you could optimize a bit with
WHERE CONCAT(course_tag, course_name) LIKE ?
I just discovered this, I use MySQL as my database.
When i do something like:
$query = $this->db->where('id', '6rubbish')->get('posts', 1);
it generates and executes this SQL:
SELECT *
FROM (`posts`)
WHERE `id` = '6rubbish'
LIMIT 1
The surprising thing is that it actually fetches the post with the ID 6.
I find this very vulnerable in same cases because i'm trying to exactly match the ID, not to do a LIKE query.
Any ideas?
Yes.
Read Type Conversion in Expression Evaluation
Use intval() PHP function to extract the integer part of the variable
Or use is_int to exclude any variable that is not a pure integer
But the origin of the problem is that your query generator library doesn't understand the variable types, PHP being a dynamic typed language doesn't help too.
I don't know what library you're using, maybe there is an option to tell that you're passing an int? It should protect you from SQL injection, I hope, try with:
$query = $this->db->where('id', "don't")->get('posts', 1);
and see if the generated SQL has the single quoted escaped (doubled or preceded by backslash).
That is because SELECT 6 = '6rubbish' will give you true, and your id is number type.
Your id field is, no doubt, a numeric data type.
When MySQL evaluates expressions, it converts operands to compatible types (see docs).
'6rubbish' (a string) gets converted to 6 (a number) and, hence, you get a match.
The user has a search box.
I need to give him flexibility so he ca do a search like client and the sql for this will be
name like '%client%'
The problem is I don't want to give the user the possibility to search with % or _ wildcards.
I know I can escape them .. but is there a function to do this for any wildcard/ or other solution ?
create or replace function escape_like(text)
returns text language sql immutable strict as
$q$
select regexp_replace($1, $$([\\%_])$$, $$\\\1$$, 'g')
$q$;
Try it:
=> select escape_like($$foo%bar\foo__bar$$);
quote_like
----------------------
foo\%bar\\foo\_\_bar
(1 row)
So your query should look similar to:
select * from tablename where columnname like '%' || escape_like(?) || '%';
In MySQL you can do it with PHP:
$text_escaped = addcslashes($text, '%\\_');
I guess the same applies to PostgreSQL, but I remeber reading something on their mailing list that you need to double escape the backward slashes in order for it to work properly, I'm not sure though...
Why don't you use full text search?