How to search in SQL for cloumn with asterisk? - mysqli

I try to create advanced search to my database.
I want to do something like that: if the user type for search = overf**w
and I have in my database an cloumn that his value = overflow - show him.
this my code:
$name = str_replace('*', '_', $name);
SELECT name FROM table WHERE name LIKE CONCAT('%', ?, '%')
its not working, I dont know what the problem.

You can't use LIKE in this situation, you need to use REGEXP() to do a wildcard search. Replace * or ** with .*. To only return names that starts with the given value use ^ at the beginning of the regular expression
SELECT name
FROM actors
WHERE name REGEXP('^overf.*w')
I don't know php but your $name parameter should be set like this (in pseudo code)
$name = '^' + replace($name, '**', '.*')

Related

postgresql replace symbol for store function variable?

I find '#' can replace some string in posgresql like:
SELECT
'Record #' || i
FROM
generate_series(1, 1000) i;
The symbol '#' can replace the by i, in this SQL commands.
I want to do similar like this for function like
SELECT lo_unlink('#') || i
From
SELECT picture i FROM image where belong_to = 254;
Of course '#' there is grammar error around '#', I just want to know any placehold grammar or symbol can work in function parameter like it replace string mark '#'
The symbol # is not replaced, you are concatenating a number to a string containing this symbol.
This concatenation can occur anywhere, including when building a function parameter:
SELECT lo_unlink('#' || i)
From
SELECT picture i FROM image where belong_to = 254;
which, if i is number 1, will create (and call) lo_unlink('#1')
so you may want to use i directly:
SELECT lo_unlink(i)
From
SELECT picture i FROM image where belong_to = 254;
which, if i is number 1, will create (and call) lo_unlink(1)

PHP: extract comma separated values from MySQL

my table is:
id | id_fruit | name
2|1|orange|
3|1|apple|
23|1|banana|
34|1|ananas|
35|3|kiwi|
I want to extract all name where id_fruit=1 and print them in a form field as values in this way:
orange, apple, banana, ananas
I've tried
select concat_ws(', ', name) from fruits where id_fruit=1 but doesn't work.
Ho can I do it? thanks!
User Group_Contact function in mysql
Select group_concat(name) from my table where fruit_id=1
I think you misunderstood the concat_ws() use.
MySQL documentation about this function explains you must give every argument to join at once.
So you sql statement has no effect.
As Raja says, you can go with your back-end programming language (such as php, python or whatever you use).
You just select without the concat_ws and do the join on the back-end side.
It seems concat_ws() main use is to concat two fields from the same entry in mysql, such as the firstname and lastname (fields) for example of the same user (entry).
Simply through PHP, you can do like that!
You can while loop all the names like this.
PHP
$in = 0;
$fruits = "";
while($row = mysqli_fetch_assoc($exeutedquery)){
if($i == 0){
$fruits += $row['name'];
$i++;
}else{
$fruits += ",".$row['name'];
}
}
AND FOR SQL
SELECT STUFF
(
(select ',' + name
from
fruits
where
ID in (1,2,3)
FOR XML PATH('')
),1,1,''
)
BAM!

powershell - get a keyword from query string

I'm learning PowerShell scripting & want to extract tableName from SQL Query String. For example, I've this query -
$q = "SELECT * FROM [TestDB].[dbo].Invoice_Details where Clientname='ABC'"
where I want to extract table name i.e. it should output this - Invoice_Details
Currently, I'm doing this with following working code -
$q1 = $q -split '\[dbo\]\.'
$q2 = $q1[1] -split ' where '
write-host $q2[0] #here I get it right (Invoice_Details)
But, sometimes the query may/ may not have bracketed names like - [TestDB].[dbo].
So, I want to optimize this code so that it will work even if query containing any combination of bracketed/ bracketless tableNames
Try something like this:
$res = ([regex]'(?is)\b(?:from|into|update)\s+(\[?.+\]?\.)?\[?(\[?\w+)\]?').Matches($q)
write-host $res[0].Groups[2].Value

SELECT with substring in ON clause?

I have the following select statement in ABAP:
SELECT munic~mandt VREFER BIS AB ZZELECDATE ZZCERTDATE CONSYEAR ZDIMO ZZONE_M ZZONE_T USAGE_M USAGE_T M2MC M2MT M2RET EXEMPTMCMT EXEMPRET CHARGEMCMT
INTO corresponding fields of table GT_INSTMUNIC_F
FROM ZCI00_INSTMUNIC AS MUNIC
INNER JOIN EVER AS EV on
MUNIC~POD = EV~VREFER(9).
"where EV~BSTATUS = '14' or EV~BSTATUS = '32'.
My problem with the above statement is that does not recognize the substring/offset operation on the 'ON' clause. If i remove the '(9) then
it recognizes the field, otherwise it gives error:
Field ev~refer is unknown. It is neither in one of the specified tables
nor defined by a "DATA" statement. I have also tried doing something similar in the 'Where' clause, receiving a similar error:
LOOP AT gt_instmunic.
clear wa_gt_instmunic_f.
wa_gt_instmunic_f-mandt = gt_instmunic-mandt.
wa_gt_instmunic_f-bis = gt_instmunic-bis.
wa_gt_instmunic_f-ab = gt_instmunic-ab.
wa_gt_instmunic_f-zzelecdate = gt_instmunic-zzelecdate.
wa_gt_instmunic_f-ZZCERTDATE = gt_instmunic-ZZCERTDATE.
wa_gt_instmunic_f-CONSYEAR = gt_instmunic-CONSYEAR.
wa_gt_instmunic_f-ZDIMO = gt_instmunic-ZDIMO.
wa_gt_instmunic_f-ZZONE_M = gt_instmunic-ZZONE_M.
wa_gt_instmunic_f-ZZONE_T = gt_instmunic-ZZONE_T.
wa_gt_instmunic_f-USAGE_M = gt_instmunic-USAGE_M.
wa_gt_instmunic_f-USAGE_T = gt_instmunic-USAGE_T.
temp_pod = gt_instmunic-pod.
SELECT vrefer
FROM ever
INTO wa_gt_instmunic_f-vrefer
WHERE ( vrefer(9) LIKE temp_pod ). " PROBLEM WITH SUBSTRING
"AND ( BSTATUS = '14' OR BSTATUS = '32' ).
ENDSELECT.
WRITE: / sy-dbcnt.
WRITE: / 'wa is: ', wa_gt_instmunic_f.
WRITE: / 'wa-ever is: ', wa_gt_instmunic_f-vrefer.
APPEND wa_gt_instmunic_f TO gt_instmunic_f.
WRITE: / wa_gt_instmunic_f-vrefer.
ENDLOOP.
itab_size = lines( gt_instmunic_f ).
WRITE: / 'Internal table populated with', itab_size, ' lines'.
The basic task i want to implement is to modify a specific field on one table,
pulling values from another. They have a common field ( pod = vrefer(9) ). Thanks in advance for your time.
If you are on a late enough NetWeaver version, it works on 7.51, you can use the OpenSQL function LEFT or SUBSTRING. Your query would look something like:
SELECT munic~mandt VREFER BIS AB ZZELECDATE ZZCERTDATE CONSYEAR ZDIMO ZZONE_M ZZONE_T USAGE_M USAGE_T M2MC M2MT M2RET EXEMPTMCMT EXEMPRET CHARGEMCMT
FROM ZCI00_INSTMUNIC AS MUNIC
INNER JOIN ever AS ev
ON MUNIC~POD EQ LEFT( EV~VREFER, 9 )
INTO corresponding fields of table GT_INSTMUNIC_F.
Note that the INTO clause needs to move to the end of the command as well.
field(9) is a subset operation that is processed by the ABAP environment and can not be translated into a database-level SQL statement (at least not at the moment, but I'd be surprised if it ever will be). Your best bet is either to select the datasets separately and merge them manually (if both are approximately equally large) or pre-select one and use a FAE/IN clause.
They have a common field ( pod = vrefer(9) )
This is a wrong assumption, because they both are not fields, but a field an other thing.
If you really need to do that task through SQL, I'll suggest you to check native SQL sentences like SUBSTRING and check if you can manage to use them within an EXEC_SQL or (better) the CL_SQL* classes.

Quote raw sql in ZEND to avoid sql injection

Long story short, I have an admin section where the user can choose from multiple dropdown lists the tables and fields that must be queries in order to get some values. Therefore, the query in ZEND is performed by concatenating the strings
$query = "SELECT $fieldName1, $fieldName2 from $tableName where $fieldName1 = $value";
How can I escape the above using ZEND approach to avoid sql injection? I tried adding them all as ? and calling quoteinto but it seems this does not work on some of the variables (like table names or field names)
ZF has quoteIdentifier() specifically for this purpose:
$query = "SELECT ".$db->quoteIdentifier($fieldName1).","...
In your case you might (also) want to check against a white list of valid column names.
Use quoteInto() or Zend_db_Select::where() for the values, and for the table and column names, I would simply strip any non alpha characters and then wrap them in ` quotes prior to using them in your SQL.
Example:
// Strip non alpha and quote
$fieldName1 = '`' . preg_replace('/[^A-Za-z]/', '', $fieldName1) . '`';
$tableName = '`' . preg_replace('/[^A-Za-z]/', '', $tableName) . '`';
// ....
// Build the SQL using Zend Db Select
$db->select()->from($tableName, array($fieldName1, $fieldName2))
->where($fieldName1 . ' = ?', $value);
In SafeMysql you can make it as simple, as
$sql = "SELECT ?n, ?n from ?n where ?n = ?s";
$data = $db->getAll($sql,$fieldName1,$fieldName2, $tableName, $fieldName1, $value);
though I understand that you won't change your ZF to SafeMysql.
Nevertheless, there is one essential thing that is ought to be done manually:
I doubt you want to let users to browse users table or financial table or whatever.
So, you have to verify a passed table name against an allowed tables array.
like
$allowed = ('test1','test2');
if (!in_array($tableName, $allowed)) {
throw new _403();
}