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)
Related
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'
I need help replacing exact numbers in my database.
My table look likes this..
ID NAME IMAGES
-------------------------------
1 person1 1,2,3...101,102,103
When I use
mysql_query("UPDATE table SET images = REPLACE(images, '3,', '') WHERE id = '1'");
It removes all the 3 from all numbers that end with 3..
13, = 1
23, = 2
113, = 11
As has been mentioned already, the correct solution is to normalize the data. However if you are stuck with this table structure, you can still perform a single UPDATE statement using 3 CASE conditions to match the number at the beginning, middle, or end.
To remove it from the beginning or end of the list, you may use a SUBSTR(), and continue using REPLACE() to remove it from the middle of the list.
UPDATE
table
SET images =
CASE
/* if 3 is in the leftmost position in the list, remove first 2 chars... */
WHEN LEFT(images, 2) = '3,' THEN SUBSTR(images, 3)
/* if 3 is in the rightmost position in the list, remove last 2 chars... */
WHEN RIGHT(images, 2) = ',3' THEN SUBSTR(images, 1, LENGTH(images) - 2)
/* Otherwise replace a single 3 bounded by commas with a single comma */
ELSE REPLACE(images, ',3,', ',')
END
WHERE id = '1'
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,' ',' !'),'! ',''),' !',' ')
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);
the problem in short,
Field:ProfileItems = "action,Search,Work,Flow,pictures";
Mysql query = "SELECT ProfileItems FROM addUsers";
then I explode with , making array e.g.: array('action','search',...etc)
and create fields for ,
Result:
<form>
action : <input type=text name=action>
search : <input type=text name=search>
...etc
<input type=submit>
</form>
My problem is how can I replace names in the database with more user friendly ones (add description) to fields without using an IF statement??
//created asoc array with Key = search item and value = user friendly value
$prase = array("ABS" => "ABS (Anti lock braking System)"
,"DriverAirBag" => "Air bags");
$string= "ABS,DriverAirbag,GOGO,abs";
foreach($prase as $db=>$eu){
echo "if $db will be $eu<br>";
echo str_ireplace($eu,$db,$string);
}
echo $string;
Tried above but was an epic fail :D !.. can you please help me out ?
Having a map inside PHP is not an unreasonable approach, but you're doing the str_ireplace() backwards: it's search, replace, subject, so in your case str_ireplace($db, $eu, $string);
But just doing a str_ireplace() on a comma-separated list of strings is not ideal anyway. For one thing, imagine if after you did the substitution for ABS you then encountered another profile item that matched lock (which just so happens to appear in "Anti-lock braking system"). Oops. Now you've overwritten your earlier replacement!
How about something like this:
$prase = array("ABS" => "ABS (Anti lock braking System)"
,"DriverAirBag" => "Air bags");
$string= "ABS,DriverAirbag,GOGO,abs";
$fields = explode(',', $string);
foreach($fields as $field) {
$friendly = $field;
if (isset($phrase[$field]))
$friendly = $phrase[$field];
echo htmlspecialchars($friendly) . ': <input type="text" name="' . htmlspecialchars($field) . '" />
}
The key here is that you're handling each field separately. And you're never just doing a replacement; you're looking specifically for the keywords "ABS" or "DriverAirbag". If there's not an exact match, you don't have a human-friendly name for that item, and there's no point doing any replacement.
All this can be improved even further if you have the ability to change the database schema. Storing a comma-separated list is never desirable. You should have a table with a schema something like:
field_id (e.g., "ABS")
name (e.g., "Anti-lock Braking System")
And another table like:
user_id (I'm inferring a little here from the name addUsers — whatever field/s you have in addUser now identifying the person)
field_id (i.e., foreign key to the above field table)
Note that you may end up with many rows in this table for each person (1, 'ABS'), (1, 'DriverAirbag')
But then your query can become
SELECT field, name
FROM user_field
INNER JOIN field USING (field_id)
Now you get back one row for each field (no explode required!) and each row includes both the computer-friendly and human-friendly name.