Problems composing php sql query for postgresql table using LIKE - php

I am trying to retrieve data from a postgresql table therefore I have written a code. Now I am trying to compose the sql query but it isn't working. With my query I am trying to search in the table genes_searchterms and find all geneID matching where in the column types the value is equal to Pathway and where in the column searchterm the word aging is present.
Bellow the code to compose my query:
$sqlquery = "SELECT DISTINCT \"gene_id\" FROM \"" . \"genes_searchterms\" .
"\" WHERE ". "(\"types\" LIKE '". \"Pathway\" . "'
AND \"searchterm\" LIKE '" . \"%aging%\" ."') ";
Is there something wrong in the composition of my query? I use drupal and I don't get any errors when executing the code. I can't figure out where I got it wrong.
I use PostgreSQL 9.2.23.
In the fiddle is a part displayed of my table
https://www.db-fiddle.com/f/t7ThJ7Aen9XYzv2EtepinP/0

I've tried to get your Query up and running in db-fiddle. I also got no result, so I rechecked your condition and tried them separately. The error was in the "searchterm" condition.
You're using the ~* operator wich matches, according to the documentation, a Regex case insensitive. Since % isn't a pattern in Regex it matches "%aging%" literally. Only if you use LIKE in the query. % will be used as a wild card.
You could ether use a correct Regex or switch to LIKE.

Related

Search using REPLACE in a SELECT with PDO and .MDB ACCESS, with PHP

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);

Mysql query keyword changes to unknown character set in php in case of Mobile devices

I am using a search query for selecting names in my DB by giving a keyword.
My query is
SELECT `engine4_core_search`.* FROM `engine4_core_search` WHERE ((`engine4_core_search`.`title` LIKE "%".$text."%"))
When give " cardiff " (cardiff comes in place of $text ) as my keyword and checking the query ..it displays like
SELECT `engine4_core_search`.* FROM `engine4_core_search` WHERE ((`engine4_core_search`.`title` LIKE 'Êrdiff%'))
Is there any method to solve this.
Thanks in advance.
It seems to be you have included jQuery-mobile (because tagged in it)
In some cases jQuery-mobile replaces some strings when they attached with different patterns like " %cardiff " . It may considers to be different string set
Just remove jQuery-mobile and try for your output......

MySQL SELECT statement using PHP GET variable

I have a PHP script that is generating a MySQL select statement:
select * from words where word = 'Classic'
There is exactly one word in the words table with the variable word equal to Classic.
When my PHP page executes, I get no results from the query. If I echo the string that is being used to execute the query, cut and paste that into the SQL window in PHPMyAdmin in the database, I also get no results. However, if I re-type that EXACT string into the SQL window in PHPMyAdmin (with the same quote characters), I get the proper result of one row.
The word Classic from the select statement is gotten from a PHP GET (see code below). I can echo the $word variable, and get the correct result of 'Classic'. What am I doing wrong?
Here is my code:
<?php
require ('dbconnect.php');
$word = $_GET["word"];
$selectStr = "SELECT * FROM words WHERE word = '" . $word . "'";
if ($results = MySQL($dbName, $selectStr))
{
$rowCount = MySQL_NUMROWS($results);
}
$resultRow = MYSQL_FETCH_ROW($results);
$wordID = $resultRow[0];
?>
Please, please, please sanitize that word. mysql_real_escape_string() should do the trick.
$selectStr = "SELECT * FROM words WHERE word LIKE '" . $sanitized_word_i_promise . "'"; should work :)
Just to explain: "=" should work for exact matches. This includes uppercase / lowercase, spaces etc. You should probably trim that result first too, before using it in the query.
If you have foo stored in the database (note the space at the end) - it won't match foo, without a space. You'll want to use LIKE 'foo%' - probably.
Either way, Sourabh is right, although performance wise, this isn't a big hit when trying to match exact strings, you should look for the problem in other places first (such as, is the item in the database an exact match?).
First off you should not take any user input and directly input it into a query without sanitizing it, or using a prepared statement.
Now that we've gotten that out of the way: have you tried doing a strcmp() with the variable and your string written in? Such as
echo strcmp($_GET['word'], "Classic")
If you get a result other than 0 it means they are not the same, most likely there will be a whitespace of some sort in the $_GET variable. use trim() on it to take out whitespace. Also could be a case sensitivity issue as well.

Wildcard mysql LIKE or IN array values issue

I have the following code block which explodes a string upon spaces.
$run = explode(" ",strtolower($q));
eg. "This is the string"
Array $run look like:
(This,is,the,string)
The problems im having are:
I only want to explode the string if it has a white, something equal as using php function str_word_count($q)>1.
Unsure on how to create a single query which will work with multiple words in string and search table using any of them.
$query = "SELECT name FROM `table1` WHERE name LIKE '%". mysql_real_escape_string($run[0]) ."%' OR name LIKE '%". mysql_real_escape_string($run[1]) ."%'";
Trying to simplyfy the above query making it smaller and variable in size based on word count. Is this also a good aproach to exploding the string then preparing the sql?
I've tried using IN as well on SQL query with no good luck.
You can use MySQL's MATCH . . . AGAINST . . . to perform this kind of search:
WHERE MATCH (name) AGAINST ('this is the string')
Consult the documentation for more information.
Original solution, not helpful in this situation:
You can check out the MySQL specific function FIND_IN_SET:
WHERE FIND_IN_SET(colname, 'This,is,the,string') > 0
The value in colname cannot contain a comma, however.

Sql: search column that starts with digits

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.

Categories