Getting certain parts of a string out of a select - php

I have a database (mydb) with following data in one column:
PK:
8/10/6101+6102 (2971386)
6110/2411 (3037457)
8/10/6504 (2276770)
8/10/6403 (2724296)
-2669938
8/1/1001-1031 (2857109)
-2547251
8/9/5003-5006 (2770096)
I have to compare these data with a variable $id for example: 2724296
SELECT * FROM mydb WHERE PK = '$id';
Of course, this query won't deliver a result. Is there a easy way to compare my $id with the values in the brace and the values with no brace? A replace in the select replaces e.g. only the brace, but not the value left to the brace.
Greets, Yab86

You can use REGEXP for this. Try this query,
$query = "SELECT * FROM mydb WHERE PK REGEXP '({$id})' OR PK REGEXP '-{$id}'";

You can use below:
SELECT * FROM mydb WHERE PK LIKE '%(2724296)';
Below is little complex: using regular expression
SELECT * FROM mydb WHERE PK REGEXP '[(]2724296[)]';
See this https://dev.mysql.com/doc/refman/5.1/en/regexp.html for writing customizable regular expression.

I would try a regular expression (assuming you only want to check the number inside the brackets). Something like this should work:
\([0-9]*\)$
This will return a string that begins with ( followed by 1 or more numbers and ends with ). You should then be able to remove the brackets from the string and compare it with your variable

Related

How to select rows by substring? Similar to Google Suggest [duplicate]

I have mysql table that has a column that stores xml as a string. I need to find all tuples where the xml column contains a given string of 6 characters. Nothing else matters--all I need to know is if this 6 character string is there or not.
So it probably doesn't matter that the text is formatted as xml.
Question: how can I search within mysql?
ie
SELECT * FROM items WHERE items.xml [contains the text '123456']
Is there a way I can use the LIKE operator to do this?
You could probably use the LIKE clause to do some simple string matching:
SELECT * FROM items WHERE items.xml LIKE '%123456%'
If you need more advanced functionality, take a look at MySQL's fulltext-search functions here: http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html
Using like might take longer time so use full_text_search:
SELECT * FROM items WHERE MATCH(items.xml) AGAINST ('your_search_word')
SELECT * FROM items WHERE `items.xml` LIKE '%123456%'
The % operator in LIKE means "anything can be here".
Why not use LIKE?
SELECT * FROM items WHERE items.xml LIKE '%123456%'
you mean:
SELECT * FROM items WHERE items.xml LIKE '%123456%'
When you are using the wordpress prepare line, the above solutions do not work. This is the solution I used:
$Table_Name = $wpdb->prefix.'tablename';
$SearchField = '%'. $YourVariable . '%';
$sql_query = $wpdb->prepare("SELECT * FROM $Table_Name WHERE ColumnName LIKE %s", $SearchField) ;
$rows = $wpdb->get_results($sql_query, ARRAY_A);

How to search for a comma-separated string in a database table in mySQL

How to search for a comma-separated string in a database table in mySQL.
Suppose, I have a string in variable $facilities='breakfast,dinner,lunch' and in my database I have a string saved in a field called facilities having values breakfast,dinner,clothing,lunch,hot water.
How do I get the row having values $facilities?
Work like this i hope this is your requirement
select * from table where field_name like '%$fieldname%'
You're going to need to break apart the comma separated string first, and include a clause for each, so for that input you'd generate SQL like (assuming you want rows that have all three, and maybe other flags set):
SELECT *
FROM YourTable
WHERE FIND_IN_SET('breakfast', facilities)
AND FIND_IN_SET('dinner', facilities)
AND FIND_IN_SET('lunch', facilities)
You can break the string apart in PHP with something a little like:
$facilities='breakfast,dinner,lunch';
$desired = explode ( "," , $facilities );
And just use a loop to build your SQL
SELECT *
FROM tableName
WHERE FIND_IN_SET('lunch', 'breakfast,dinner,lunch')
EDIT:
SELECT *
FROM tableName
WHERE FIND_IN_SET('lunch', food_column)
food_column is the name of the column where the string 'breakfast,dinner,lunch' is stored

Multiple conditions in LIKE operator

i am getting multiple values in this $languages like(php,Ruby) i want spilt that and how to check that split values in this query
SELECT * FROM software_capability where languages LIKE '%$languages%'
As in other languages Mysql also supports regexp for pattern matching that could be used in such cases. I would simply create a query string separated by the delimiter (|) out of the $languages array, and use that in the query --
$query_string = implode("|", $languages);
SELECT * FROM software_capability where languages REGEXP $query_string
The result will be same using LIKE clause as given in other answer.
Try with this.
SELECT * FROM table WHERE interests LIKE ('%sports%', '%pub%')
This is syntax. Exploded your $language and put each item in '%$item%'
SELECT * FROM software_capability where CONCAT('%',languages,'%') LIKE '$languages';
assuming that $languages is 'php,Ruby'
If $languages is comma (,) separated values, then you can try with IN command of mysql
SELECT * FROM software_capability where languages IN ($languages)

PHP MySQL statment with AND and OR

I have a PHP MySQL statement and basically what I want is to check for that table element matches and then check a second table element matches or a third table element matches, sort of like this
if ref=ref (AND page=page OR allpages=1)
that means search for all pages with ref=ref and then in that recordset check if page=page or if all pages=1
so MySQL statement is this:
$sql=mysql_query("SELECT * FROM content WHERE ref='$ref' AND page_ref='$page_ref' OR allPages='1');
But it is taking records from the db that don’t match the ref but allpages=1
Is there some way of bracketing this or restructuring the statement?
Your if ref=ref (AND page=page OR allpages=1) was nearly right, but you want the AND out of the brackets:
if ref=ref AND (page=page OR allpages=1)
Implemented:
$sql=mysql_query("SELECT * FROM content WHERE ref='$ref' AND (page_ref='$page_ref' OR allPages='1')");
Note: you were missing a closing " from the query as well (though I suspect this was a copy error when creating the question)
Further improvement (concatenation and backticks):
$sql=mysql_query("SELECT * FROM `content` WHERE `ref`='".$ref."' AND (`page_ref`='".$page_ref."' OR `allPages`=1)");
Simply add brackets like this:
SELECT * FROM content
WHERE ref='ref'
AND (page_ref='page_ref' OR allPages='1')
-------^------------------------------------^----Add here
So your whole query should be:
$sql=mysql_query("SELECT * FROM content WHERE ref='$ref' AND (page_ref='$page_ref' OR allPages='1')");
User Operator Precedance.
The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18.
"SELECT * FROM content WHERE ref='".$ref."' AND (page_ref='".$page_ref."' OR allPages=1")
I think
SELECT * FROM content WHERE ref='$ref' AND (page_ref='$page_ref' OR allPages='1')
it is a priority matter. You can read about operators precedence in the corresponding manual page.
Also, remember, that mysql_* functions are officially deprecated, so use mysqli_ or PDO instead.
You can add brackets to your mySQL statement in just the same way as you add them to a PHP statement. Just make sure your expression is bracketed in the same way as your desired logic.
$sql=mysql_query("SELECT * FROM content WHERE ref='$ref' AND (page_ref='$page_ref' OR allPages='1')");
You should set braces around the OR comparison:
WHERE ref='$ref' AND ( page_ref='$page_ref' OR allPages='1' )

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