Trim extra space from column Mysql - php

I have a old database in which column categories is stored in bad shape ... with extra space in them, example
Hotels in London
Hotels in Manchester
is there a way i can alter this space inside the table ... if i can remove extra space from categories (middle space) to get output like this
Hotels in London
Thx

You can use the REPLACE function like
update table set columnName= REPLACE(columnName,' ',' ')

Pull the data down into values that you can do work on then remove the extra white space using:
$foo = trim(preg_replace( '/\s+/', ' ', $foo ));
then write it back to the DB.

I had the similar situation where i had to remove the extra spaces while searching value for a particular field.
I have used replace function of mysql, like this
SELECT * FROM `tableName` WHERE post_id = 'xxx' AND replace(`fieldName`,' ','') Like '%JobOppurtunity%' ;
Here what replace does, it recursively removes all the spaces in the fieldName and concatenates the field value and then searches my concatenated string after LIKE keyword.
So if I had field value 'Job Oppurtunity', it will convert it into 'JobOppurtunity' and obviously I would have already concatenated my search string by any string function or regular expression. Like it did this way
$txt_search_qry = trim(preg_replace( '/\s+/', '', $txt_search_qry));

Another quick and simple method I found is this:
REPLACE(REPLACE(REPLACE(columnName,' ',' !'),'! ',''),' !',' ')

Related

select category after link remove special characters?

I have a page to show some people's name, so user can click and see their related posts.
The problem is people with ' or . in the name or any other special character.
To create the URL I need to remove this characters:
Marie E.A
Josh O'Reilly
php to create the link:
$categorialink = strtolower($categoria);
$categorialink = str_replace(' ', '_', $categorialink);
$categorialink = preg_replace('/[^A-Za-z0-9\_-]/', '', $categorialink);
will become:
www.mypage.com/person/marie_ea
www.mypage.com/person/josh_oreilly
the problem is to get this values from mysql, Mysql record the name as it is (Marie E.A) and I can't go back to the original person's name.
mysql LIKE could help, but can open another person page by select something similar eg: Marie E.B instead of Marie E.A.
$categoryp = $_GET['categoria'];
$category = str_replace("_", " ", $categoryp);
SELECT id, categoria FROM categoria where categoria = 'marie ea' limit 1 //$category value - return nothing
how to solve this?
Just use urlencode () . That will translate string by only replacing letters, not deleting them. Later if You need to get previous name, just use rawurldecode() .

Add string before and after array values for php>mysql searching

I have an html form with multiple checkboxes. I pass those to php...
The values will come in like "G,BW" for example ("BW,G" needs to match as well)
in check.php, I need to take the values from $_GET and modify them for an sql query...
<?php
if(!empty($_GET['wireColor'])) {
foreach($_GET['wireColor'] as $colors) {
echo $colors; //make sure it's right, then comment out
}
}
$colors = rtrim($colors, ','); //Get rid of trailing , - not working right
$wireSearch = '\'REGEXP \'.*(^|,).$wireColor.(,|$)\''; //Trying to add the sql bits to pass to the query.
Ideally to get this passed:
$colors_lookup_sql = "SELECT * FROM parts WHERE ( wire_colors REGEXP '.*(^|,)$wireSearch(,|$)' and wire_colors REGEXP '.*(^|,)$wireSearch(,|$)' );";
Here's how the query should look at the end:
SELECT * FROM parts WHERE ( wire_colors REGEXP '.*(^|,)G(,|$)' and wire_colors REGEXP '.*(^|,)BW(,|$)' );
I'm having a hard time getting the regex bits into the query.
UPDATE
Here's what I have now:
<?php
if(!empty($_GET['wireColor'])) {
foreach($_GET['wireColor'] as $colors) {
$wireSearch = ' REGEXP \'.*(^|,)' .$colors.'(,|$)\' AND ';
}
}
$Search = rtrim($wireSearch, 'AND'); //Trying to trim the last "AND"
$colors_lookup_sql = "SELECT * FROM parts WHERE ( wire_colors $wireSearch% );";
Which gives me mostly what I need, but print/echo the results and I get:
$wireSearch ends up as: REGEXP '.*(^|,)G(,|$)' AND REGEXP '.*(^|,)BW(,|$)' AND Which is great - I just need to nuke the last "AND". The trim above replaces it with the second value instead though. Weird.
and $colors_lookup_sql ends up as: SELECT * FROM parts WHERE ( wire_colors REGEXP '.*(^|,)BW(,|$)' AND % );
BUt for some reason the first value in the array goes away, which I don't understand since it was present before the sql statement.
I'm not sure about the REGEX inside the query since I haven't used it but:
$wireSearch = '\'REGEXP \'.*(^|,).$wireColor.(,|$)\'';
Here you have a problem, the variable $wireColor is inside a string, and you are using ' so anything inside is not read as a variable, it should be something like:
$wireSearch = '\'REGEXP \'.*(^|,)'.$wireColor.'(,|$)\'';
I cant say I entirely understand how your data is being stored, and I havent worked with REGEX much myself, but perhaps something like this would be a bit easier to work with:
$wireSearch = explode(",", $_GET['wireColor']);
$query = "SELECT * FROM parts WHERE wire_colors LIKE '%$wireSearch[0]%'
AND wire_colors LIKE '%$wireSearch[1]%'";
Not sure if this helps but I thought id throw in the idea.
I guess mysql regex supports word boundaries, how about:
wire_colors REGEX '\bBW\b' and wire_colors regex '\bW\b'

MySql Search With Special Character

I searching records from database using MySql as -
SELECT * FROM tab WHERE col LIKE '%myvalue%';
This is working fine and showing all the records having myvalue.
Now the problem is i have some records like my'value, myva'lue, myval-ue and my-value And also want to include these records in search. Also when i search for my'value then it should show myvalue and my-value.
How to achieve this? Any Help. Is it possible to do using LIKE operator?
As you are using PHP you should do the following, if someone uses your search:
Get the search-term via $_POST
Remove all special characters from the search-term (my'value becomes myvalue)
Replace the search term with MySQL wildcards (myvalue becomes %m%y%v%a%l%u%e%)
Execute SELECT * FROM tab WHERE col LIKE '%m%y%v%a%l%u%e%'
Any of the other solutions will not match all your requirements.
SQL Fiddle: http://sqlfiddle.com/#!2/20f811/2
Use
SELECT * FROM tab WHERE col LIKE '%myvalue%' OR col LIKE '%my_value%'
The underscore _ is a single character wildcard.
How about this?
SELECT * FROM tab WHERE col LIKE 'my%' OR col LIKE '%value'
this will check col should start with my and end with value.
Demo
Edit 1
As there can be any special character and regexp don't work with MySQL, I would suggest you to do what you want to achieve in PHP by replacing special character by null and then matching the string with myvalue.
Hope this helps you.
Edit 2
I don't know php exactly, but can tell you what to do little bit.
mysql = "SELECT id, col FROM tab WHERE col LIKE '%my%' OR col LIKE '%value%'";
rs = mysql.execute();
String newString = "";
while (rs.next()) {
newString = rs.getString(2);
newString = new string after replacing special characters using regexp
if (newString.equals("myvalue")) {
// your code here..... this is place what you wanted.
}
}
Got this...
PHP Part
$term = str_replace('-','',str_replace(',', '', str_replace('\'', '', $term)));
MySql Part
SELECT *
FROM tab
WHERE ((REPLACE(REPLACE(REPLACE(col, '\'', ''), ',', ''), '-', '') LIKE "%$term%")
OR (col LIKE "%$term%"));
See this demo.

How to check if a string already exists in mysql (All word order options)?

Let's say i check if
$strig = "how can i do this";
already exists in my database with all words order options?
Like:
"how i can do this"
or
"i do this can how"
...
...
my database looks like:
id string
1 how can i do this
2 hello how are you
3 how i can do this world
4 another title
etc etc
Thanks
The number of possible combinations is n! (120 in your sample) so checking if this string already exists is quite complex task.
I would recommend to use the following algorithm:
Add new column StringHash to your table
On insert order your string (e.g. alphabetically), calculate its hash and store in StringHash:
"how can i do this" => "can do how i this" => md5("can+do+how+i+this")
If you want to check if a certain string exists in the db then again calculate its hash as described above and query the db on YourTable.StringHash
This is a tricky problem if you want to fix this in sql only, but that aside:
As #er.anuragjain says, you can do a query with LIKE %word%, but you would also get a hit on your example '3'.
So if you have a query like this:
SELECT * FROM table WHERE
column LIKE '%how%'
AND column LIKE '%can%'
AND column LIKE '%i%'
AND column LIKE '%do%'
AND column LIKE '%this%'
Then you also get number 3. So you need to check if there are no other words. You can do this by checking the word count (if you have 5 words and all of your words are in there, you are done.).
Checking wordcount is not trivial, but there is a trick. From several sources*:
SELECT LENGTH(total_words) - LENGTH(REPLACE(total_words, ' ', ''))+1
FROM tbl_test;
should do the trick. So check the LIKE's, and check the wordcount, and you're done. But I'm not really sure this is a pretty sollution :)
http://www.webtechquery.com/index.php/2010/03/count-number-of-words-in-mysql-mysql-words-count/
and http://www.mwasif.com/2008/12/count-number-of-words-in-a-mysql-column/
(random google hits :) )
you can ask if the string where you are searching in, contains: "how" and "can" and "I" and "do" and "this"
something like this:(I don't know the syntax in mysql but see the concept)
if(string.contain("how")&&
string.contain("can")&&
string.contain("I")&&
string.contain("do")&&
string.contain("this"))
{
//you find the string
}
If you are using mysql then try this..
select * from tablename where columnname Like '%how%' AND columnname LIKE '%can%' AND columnname LIKE '%I'% AND columnname LIKE '%DO'% AND columnname LIKE '%This'%;
Here if u have dynamic value in $string then first convert it into an array spliting by space.then create a $condition varriable from the array and append that in select * from tablename where and run that query.
thanks
should be the wildcard call in mysql
select * From tablename Where columnname LIKE '%how%'
you can use regex first crate a function like this
public function part($str){
$str = str_replace('‌',' ',$str);
$arr = explode(' ',$str);
$rejex = '';
foreach($arr as $item){
$rejex .= "(?=.*$item)";
}
return $rejex;
}
and then use sql regex
$sql = "SELECT * FROM `table` WHERE `column` REGEXP ".part($str);

Remove values in comma separated list from database

I have a table in my MySQL database called 'children'. In that table is a row called 'wishes' (a comma separated list of the child's wishlist items). I need to be able to update that list so that it only removes one value. i.e. the list = Size 12 regular jeans, Surfboard, Red Sox Baseball Cap; I want to remove Surfboard.
My query right now looks like this
$select = mysql_query('SELECT * FROM children WHERE caseNumber="'.$caseNum.'" LIMIT 1 ');
$row = mysql_fetch_array($select);
foreach ($wish as $w) {
$allWishes = $row['wishes'];
$newWishes = str_replace($w, '', $allWishes);
$update = mysql_query("UPDATE children SET wishes='$newWishes' WHERE caseNum='".$caseNum."'");
}
But the UPDATE query isn't removing anything. How can I do what I need?
Using these user-defined REGEXP_REPLACE() functions, you may be able to replace it with an empty string:
UPDATE children SET wishes = REGEXP_REPLACE(wishes, '(,(\s)?)?Surfboard', '') WHERE caseNum='whatever';
Unfortunately, you cannot just use plain old REPLACE() because you don't know where in the string 'Surfboard' appears. In fact, the regex above would probably need additional tweaking if 'Surfboard' occurs at the beginning or end.
Perhaps you could trim off leading and trailing commas left over like this:
UPDATE children SET wishes = TRIM(BOTH ',' FROM REGEXP_REPLACE(wishes, '(,(\s)?)?Surfboard', '')) WHERE caseNum='whatever';
So what's going on here? The regex removes 'Surfboard' plus an optional comma & space before it. Then the surrounding TRIM() function eliminates a possible leading comma in case 'Surfboard' occurred at the beginning of the string. That could probably be handled by the regex as well, but frankly, I'm too tired to puzzle it out.
Note, I've never used these myself and cannot vouch for their effectiveness or robustness, but it is a place to start. And, as others are mentioning in the comments, you really should have these in a normalized wishlist table, rather than as a comma-separated string.
Update
Thinking about this more, I'm more partial to just forcing the use of built-in REPLACE() and then cleaning out the extra comma where you may get two commas in a row. This is looking for two commas side by side, as though there had been no spaces separating your original list items. If the items had been separated by commas and spaces, change ',,' to ', ,' in the outer REPLACE() call.
UPDATE children SET wishes = TRIM(BOTH ',' FROM REPLACE(REPLACE(wishes, 'Surfboard', ''), ',,', ',')) WHERE caseNum='whatever';
Not exactly a direct answer to your question, but like Daren says it's be better having wishes as its own table. Maybe you could change your database schema so you have 3 tables, for instance:
children
-> caseNum
-> childName
wishes
-> caseNum
-> wishId
-> wishName
childrensWishes
-> caseNum
-> wishId
Then to add or delete a wish for a child, you just add or delete the relevant row from childrensWishes. Your current design makes it difficult to manipulate (as you're finding), plus leaves you at risk for inconsistent data.
As a more direct answer, you could fix your current way by getting the list of wishes, explode() 'ing them, removing the one you don't want from the array and implode() 'ing it back to a string to update the database.
Make wishes table have this format:
caseNumber,wish
Then you get all of a child's wishes like this:
SELECT * FROM children c left join wishes w on c.caseNumber = w.caseNumber WHERE c.caseNumber= ?
Removing a wish becomes:
DELETE from wishes where caseNumber = ?
Adding a wish becomes:
INSERT into wishes (caseNumber,wish) values (?,?)
Returning one wish becomes:
SELECT * FROM children c left join wishes w on c.caseNumber = w.caseNumber WHERE c.caseNumber= ? LIMIT 1
Having the wishes indexed in an array which is thereafter serialized could be an idea, otherwise you would need to retrieve the string, slice it, remove the part you don't want, then concatenate the remains. This can be done by using the explode() function.
If you were to use an array, you would retrieve the array and then sort through it with a loop like this:
// Wishes array:
// Array (
// [0] Regular Jeans
// [1] Surfboard
// [2] Red Sox Baseball Cap
// )
$wishes = $row['wishes']; // This is a serialized array taken from the database
$wishes = unserialize($wishes);
foreach ($wishes as $key => $value) {
if ($value == 'Surfboard') {
unset($wishes[$key]);
break;
}
}
$wishes = serialize($wishes);
// Update database
Keep in mind that index [1] now won't exist in the array, so if you wish to have a clean array you should loop through the array and make it create a new array by itself:
foreach ($wishes as $wishes) {
$newArray[] = $wishes;
}
I think the best answer to such issue is here
The best way to remove value from SET field?
query should be like this which covers the ,value or value, or only value in the comma separated column
UPDATE yourtable
SET
categories =
TRIM(BOTH ',' FROM
REPLACE(
REPLACE(CONCAT(',',REPLACE(col, ',', ',,'), ','),',2,', ''), ',,', ',')
)
WHERE
FIND_IN_SET('2', categories)
Here you can have your condition in where clause. for more details refer above link.
You can create function like this:
CREATE FUNCTION `remove_from_set`(v int,lst longtext) RETURNS longtext CHARSET utf8
BEGIN
set #lst=REPLACE(#lst, ',,', ',');
set #lng=LENGTH(#lst) - LENGTH(REPLACE(#lst, ',', ''))+1;
set #p=find_in_set(#v,#lst);
set #l=SUBSTRING_INDEX( #lst, ',', #p-1);
set #r=SUBSTRING_INDEX( #lst, ',', #p-#lng);
IF #l!='' AND #r!='' THEN
return CONCAT(#l,',',#r);
ELSE
RETURN CONCAT(#l,'',#r);
END IF;
END
Using:
SELECT remove_from_set('1,,2,3,4,5,6',1)

Categories