I have query which search for database, that is
$linkcdb = $wpdb->query($wpdb->prepare("SELECT wp_link_factor WHERE wp_link_chk = %s", $u));
where $u = is nay link;
for example;
$u = www.kaka.com
$u = popopo.com
$u = http://jajaja.com
I have a data base in which www, http and .com is in the column of table and the column name is wp_link_chk
Now the problem I am facing is the user input is a complete link like www.example.com while in database I had only .com, http and www
What I want is that how I compare my complete sentence and see if the sentence have needle http, or www or .com in it ?
The function that do this is stristr($u,'http') so how I am going to use this functionality in data base, I mean how i am going to check the column of wp_link_chk as a needle against my sentence ?
Using the MySQL function LOCATE you could use something like
... WHERE LOCATE( wp_link_chk, :userInput ) > 0
Edit: Note that this approach may of course return multiple records, for instance if "http://www.example.com" is matched against "http", "www", and ".com".
Well, the closest way to match these is to use the mysql LIKE function.
The actual statement would be something like
SELECT wp_link_factor WHERE wp_link_chk LIKE %www.example.com%
But since you are using wordpress prepared statements, use it like this:
$linkcdb = $wpdb->query($wpdb->prepare("SELECT wp_link_factor WHERE wp_link_chk LIKE %s", '%' . $u . '%'));
-- UPDATE --
For the sake of completion, you can use REGEXP matching to select rows that contains either http, www or .com in the wp_link_chk column using the following query.
SELECT wp_link_factor WHERE wp_link_chk REGEXP '(http)|(www)|(\.com)'
Related
I'm trying to write a mysql query that will match names from a table and the name in the database can contain dots or no dots. So, for example I would like my query string fast to match all of these: fast, f.ast, f.a.s.t etc.
I use PHP, with PDO connecting to a .MDB database.
I tried what I found here, with no success (I get error):
SELECT * FROM table WHERE replace(col_name, '.', '') LIKE "%fast%"
I think PDO for MDB databases is missing some functions :(
Any solution?
Thanks to Doug, I solved with:
$variable = implode("[.]", str_split($variable)) . "[.]";
and:
SELECT * FROM table
WHERE
col_name LIKE "%" . $variable ."%";
You cannot run the replace() function unless you are running the query through Access itself. You do however have a possible alternative, try the following:
SELECT * FROM table
WHERE
col_name LIKE "%fast%"
OR col_name LIKE "%f[.]a[.]s[.]t%";
The square brackets define an optional .
Or alternatively do it at PHP level with:
str_replace('.','',$var);
the question might be a bit confusing, so here is what i have:
i insert in the database the previous link where a person came from like tihs:
$came_from = $_SERVER['HTTP_REFERER']; // get previous link
if the link is from google.com it will come like this:
http://www.google.com/#sclient=psy&hl=en&source=hp&q=this+is+a+test&pbx=1&oq=this+is+a+teat&aq=f&aqi=g-s1g-v1&aql=1&gs_sm=s&gs_upl=887l82702l3.10.3.1l17l0&bav=on.2,or.r_gc.r_pw.r_cp.&fp=c3d3303&biw=1920&bih=995
if we look inside we can find q=this+is+a+testas beeing the keywords that i search for.
my question is how can i create a query to return http://www.google.com/ | this+is+a+test ?
i know that the keywords have the + sign in between them.
so far i came up with this, but not exactly what i wanted:
SELECT SUBSTRING_INDEX (table, '+', 1), table FROM table.table WHERE table LIKE '%+%' LIMIT 20
any ideas?
thanks
edit: what happend is that sometimes i get some other url's that don't have q= but maybe seearch=, so i want to keep track of the + sign
As it's been pointed out, you can't reliably get the keywords without supplying the parameters to look for. Here's what I would do:
$url = 'http://www.google.com/#sclient=psy&hl=en&source=hp&q=this+is+a+test&pbx=1&oq=this+is+a+teat&aq=f&aqi=g-s1g-v1&aql=1&gs_sm=s&gs_upl=887l82702l3.10.3.1l17l0&bav=on.2,or.r_gc.r_pw.r_cp.&fp=c3d3303&biw=1920&bih=995';
$possible = array('q', 'ssearch', 'oq');
$query_str = NULL;
foreach ($possible as $search) {
if (isset($arr[$search])) {
$query_str = $arr[$search];
break;
}
}
Basically all this does is parse the url using PHP's parse_str() and look for the parameter q. If it's not there, it uses ssearch, and then oq. You can add more of them if you need to. If by the end of it it's not found, $query_str will be NULL.
Unless you have a very compelling reason to do it with MySQL only, just process everything on the PHP side. Databases are made to store data, not process it. What I would do is have PHP figure out the search engine and the keywords used and insert those into the DB, as separate fields. ie, have a table like so:
search_engine | query_str
------------- | -----------
google | test
yahoo | something
...
If you know that you need q=... then you can use regexp. I will update post if that's what you need.
As everyone is saying, you need to use the key value (in your example, q). In MySQL, you can do something like this:
SELECT SUBSTRING_INDEX(table, '?q=', -1), table FROM table.table WHERE table LIKE '?' LIMIT 20
I'd also suggest you rename your table column to something other than 'table'.
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?
$value = 'http://www.mydomain.com/this-is-page-one'
I have a field in my mysql table called "urls" which stores different urls inside, like:
http://www.bdsada.com/dsadsfsaf
http://www.comddsad.com/dsadacsdfs
and so on
I want to best match my value with on of the urls. - do an sql query
Maybe the number of repeatting letters.
Please give an actual example.... pleaseee
Not sure exactly what you mean by the 'best match'. Say that you are storing the urls in the database as listed above (http://www.website.com/extension). Also, that the input may or may not include the 'http://', 'www.', or any additional GET variables in the URL. Before you submit the string for the database query, I would do the following:
To strip the 'http://' or 'https://' from the url.
$valueStrip = explode("//",$value);
$value = $valueStrip[1];
To strip out any get variables
$valueStrip = explode("?",$value);
$value = $valueStrip[0];
Also, make sure you clean it for any SQL injection attack, this should work
$value = mysql_real_escape_string($value);
Let assume that 'url' is the name of the table and 'domainName' is the column name for the actual domain name. So, your query could look like this
$query = mysql_fetch_array(mysql_query("SELECT url FROM domainName WHERE url LIKE '%$value%'"));
I should note that I haven't tested the code and it could be made more efficient.
I have a function below which works perfectly, but now the client came back and asked that the number only be taken to do the search because most of his clients won't type in the suffix "h" or whatever it may be as per my example below:
38039 or 38039h
However he also said he only has one group of product codes which begin with "T" so they could be typing in "T760" in which case we would need the prefix.
My code below does a search on the exact product currently, can anyone help me work in these examples?
<?php
//Find Stock Value
function checkstock($prodCode) {
$prodCode = strtoupper($prodCode);
require '../../../../config.php';
$dbh = new PDO(DB_DSN, DB_USER, DB_PASS);
$sql = "SELECT * FROM isproducts WHERE prodCode = '".
$prodCode."' AND AllowSalesOrder = '1'";
$stmt = $dbh->query($sql);
$obj = $stmt->fetch(PDO::FETCH_OBJ);
$count = $stmt->rowCount();
echo ($count == 1 ?
ROUND($obj->FreeStockQuantity, 0) : 'Invalid product code '.$prodCode.'');
}
//Call Stock Function
checkstock($_POST['productcode']);
?>
Change the query to like below ?
SELECT * FROM isproducts
WHERE
(
prodCode='{$prodCode}' // for product with prefix or suffix
OR prodCode LIKE '{$prodCode}%' // without suffix
OR prodCode='T{$prodCode}' // without prefix
)
AND AllowSalesOrder = ''";
Wild-card by single character
OR prodCode LIKE '{$prodCode}_' // single character wild-card
It seems that you may have products with the same number but not the same suffix? like 8512n and 8512h ?
You could use LIKE '%$code%'
$sql = "SELECT * FROM isproducts WHERE prodCode LIKE '%".$prodCode."%' AND AllowSalesOrder = ''";
and I think its the more secure way in your case, so that all products containing the number will appear, regardless of suffix or prefix.
The above may return more than one product, so the user still has to choose which one it is he is actually looking for.
You can use % wild card for this kind of problem.
check this out....
http://www.w3schools.com/SQL/sql_wildcards.asp
it might be useful... :-)
In some of my code I use the following strategy:
# psuedo-code ... NOT intended for real use:
SELECT COUNT(*) FROM someTable WHERE someColumn = "{XXX}"
# If that returns exactly one than use the corresponding query
SELECT COUNT(*) FROM someTable WHERE someColumn LIKE "{XXX}"
# If that returns exactly one then use it
SELECT COUNT(*) FROM someTable WHERE someColumn LIKE "{XXX}%"
# If that returns exactly one then use it
SELECT COUNT(*) FROM someTable WHERE someColumn LIKE "%{XXX}%"
# If that returns exactly one then use it
... (where {XXX} is the placeholder for the user supplied search term).
The idea here is that I first try a precise match, then I try it under the assumption that the term already may contain SQL wildcards, then I try suffixing the % wild card and finally I try wrapping it with % wild cards.
At any point if I've found an unambiguous match then I use it. If I find more than one match at any point (not shown in the psuedo-code here) then I might throw an exception or I might return them or a subset of them based on the specifics of what I'm doing.
(In reality I'm using the parameter interpolation features of Python or Perl or sanitizing my inputs to allow wild cards while preventing SQL injections; so the code doesn't look like what I'm showing here. This is just to convey the general idea).
My goal is to allow my scripts to be called with the minimum unambiguous arguments supplied which sounds roughly similar to what your clients are requesting here.
From a usability perspective most users will get the first characters of any input right. So exact match following by suffixed wildcard match is most likely to succeed most of the time. In my case my users are likely to be familiar with SQL wildcards and may prefer to use them to construct their own unambiguous match; and logically that attempt has to be inserted before I start suffixing or wrapping it with my own wildcards.
This is why I use this specific sequence of matching attempts.