I would like to know if there is a better way than :
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE('p%a_t*er?', '\\', '\\\\'), '%', '\%'), '_', '\_'), '*', '%'), '?', '_')
To transform standard search patterns * and ? to the LIKE equivalents % and _ in MySQL ?
There isn't a shorter method to perform multiple-character replacements directly in MySQL. There are alternatives such as User-Defined-Functions (UDFs), but I'm doubtful that any would be beneficial to your exact purpose.
My suggestion would be to perform the text replacement prior-to querying the database, if acceptable.
In PHP, this could be done with:
$searchQuery = $_GET['q'];
$searchQuery = str_replace(array('*', '?'), array('%', '_'), $searchQuery);
// perform your query as normal
In ASP, you could try:
string searchQuery = Request.QueryString["q"];
searchQuery = searchQuery.Replace("*", "%").Replace("?", "_");
// perform your query as normal
Though, both method aren't super-short, they do make it a little easier to read and also won't add any time to your db-query. Also, doing the replacement prior to the query will allow you to replace before the string is sanitized so you won't need to replace the \ as you do in your existing query - which saves you one replacement!
Instead of like you can use regexp of Mysql like this:
select * from my_table where col_name regexp 'p%a_t*er?';
While using regexp there is no need to do all those replacements to make your string like friendly.
Related
I need help in mysql query, i written this query
select * from post where content REGEXP '^q'
this query is working but it also includes spaces in filter, what i want to do if any content string like "qqqqqq" or "qqqq" or "qqq" or "qq" or "q" for this string only it should have to filter, right now what is happening if i have string like "qqqq qq" then also it is giving me the result, it should not consider that space, can anyone please help me to resolve this issue ?
You can fix your regexp like next:
select * from post where content REGEXP '^q+$';
This regular expression mean the string starts with q and contain only 1 or more q symbols till end of string
Test it on SQLize.online
Try Using this ^q+(?![\s])+$ Regular Expression.
Above RegExp will check for string starting with q and without space.
You don't really need a regex for this. String functions are likely to be more efficient. You can replace all "q"s with empty strings, and ensure that that resulting string is empty:
select * from post where replace(content, 'q', '') = ''
Note that this also allows the empty string. If you want to avoid that, then:
select * from post where content <> '' and replace(content, 'q', '') = ''
I am new to python and currently learning to use SQL with python. I have the following code:
word = input("Enter a word: ")
query = cursor.execute("SELECT * FROM Dictionary WHERE Expression LIKE '%s%' " % word)
results = cursor.fetchall()
The second line throws an error since I don't think I can use '%s%' like that? How would I change this so as to be able to make this work? I want to be able to return all related entries to the users input. So if the user inputs "rain", then I want the query to return all possible results e.g. "raining", "rainy" etc. Thank you.
You can try
query = cursor.execute(f"SELECT * FROM Dictionary WHERE Expression LIKE '%{word}%' ")
You should use cursor.execute() parameter substitution rather than string formatting, to prevent SQL injection.
Then use CONCAT() to surround the search string with %.
query = cursor.execute("SELECT * FROM Dictionary WHERE Expression LIKE CONCAT('%', %s, '%' "), (word,))
I have this query:
$sql = "
INSERT INTO table SET
name = '$name',
sku = '$number',
description = '$desc'
";
But the rows containing some special characters (in my case this ') are not inserted.. How I can solve?
Thanks in advance.
When you construct your query, you need to escape the data you are inserting.
You need to at least use addslashes() function in PHP, like this:
$sql = "INSERT INTO table SET name = '".addslashes($name)."', sku = '".addslashes($number)."', description = '".addslashes($desc)."'";
However more correct way is to use a different function than addslashes, which would properly handle all characters in the data, not only apostrophes.
I am using my custom 'escape' function like this:
function escape($text)
{
return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $text);
}
So using this function, you would write:
$sql = "INSERT INTO table SET name = '".escape($name)."', sku = '".escape($number)."', description = '".escape($desc)."'";
You must use parameterised queries instead of manually appending those values. Currently if name, number or description would contain any sql it would get executed.
A lot more detailed answer is in How can I prevent SQL injection in PHP?
Read about escaping characters in mysql. I think it is done with \
I need an sql select statement to retrieve 04:30 and test.zip from this string:
{"TIME":"04:30","DATE":"11\/25\/2013","FILENAME":["test.zip"]}
use this \[(.*?)\]
it return value between [ and ]
and for 04:30 use TIME":(.*?),
it return value after "TIME":
Can't you just decode it and use PHP? (assuming you can't change the way it's stored in the db)
<?php
$str = '{"TIME":"04:30","DATE":"11/25/2013","FILENAME":["test.zip"]}';
$o = json_decode($str);
$time = $o->TIME;
$file = $o->FILENAME[0];
var_dump($time); //"04:30"
var_dump($file); //"test.zip"
Regex replaces etc in MySQL require a UDF (user-defined function) mysql-udf-regexp
If none of the above are viable solutions (change DB structure, do it with PHP, use a MySQL UDF), you'll need to get creative. It would require a known, static format of that string, but you could replace some parts and substring others. For example:
SELECT SUBSTRING(REPLACE(`column_name`,'{"TIME":"',''),1,5) AS `time` FROM `table_name`
File is more complex, this example assuming only one filename in the array
SELECT REPLACE(SUBSTRING(`column_name`,LOCATE('"FILENAME":["',`column_name`)+13),'"]}','') AS `file` FROM `table_name`
Those two field selections get 04:30 and test.zip respectively (you can of course use those functions in the same statement, rather than separately like I have, by comma separating them)
Is it possible to use this sql query?
select ([discount_type]='Percent') ? [Percent]+'%' : [Amount]+'RS' as [Discount] from [admin].[discount] where [discount_id]=2
You can make a CASE (which is pretty much like a switch in many other languages)
SELECT
CASE [discount_type]
WHEN 'Percent' THEN [Percent] + '%'
ELSE [Amount] + 'RS' END as [Discount]
FROM [admin].[discount]
WHERE [discount_id] = 2
Note that the rest of the query uses your code as is, i.e. assuming that Percent can be concatenated with a string without prior conversion.