Replace Content using MySQL - mysql

In many of my column I have some data like this :
"Some Data. [content]Some Content[/content] Another Data"
I want to remove the substring which starts with [content] and ends with [/content]. The result should be :
"Some Data. Another Data"
I know it is possible by using MySQL replace() with Reg Ex but I don't how to use it.
Any help would be appreciated.

first get all the string between that string and after that you can able to replace it:
SELECT substring_index(substring_index(field, 'content', -1), '/content', 1) FROM table_name
after run this query, you get between string of [content] and [/content]
after that you just have to update one bye one using foreach loop with use of this query
UPDATE table_name SET field = REPLACE(field, 'content', 'content-that-will-replace-it') WHERE INSTR(field, 'content') > 0

Related

prepend a string to a column value before specific character in MySQL

Imagine I have a table which has a Params column and it contains settings of my gallery. I want to add 2 other properties automatically with MySQL query.
I have already test this query but it will add my new properties at the first of the column value which is incorrect :
UPDATE table
SET params=CONCAT(', "slider_fullscreen_button_skin": "myTheme", "slider_zoompanel_skin": "myTheme"',params)
WHERE params NOT LIKE '%myTheme%';
let's say I have this value on my column :
{"title":"Bessariabian","alias":"Bessariabian","category":"1103","full_width":"false"}
I want my value change to something like this:
{"title":"Bessariabian","alias":"Bessariabian","category":"1103","full_width":"false", "slider_fullscreen_button_skin": "myTheme", "slider_zoompanel_skin": "myTheme"}
I want to make a query which adds the new properties at the end of the value before } location.
How I can handle this?
Use Substring_Index() function to get the Substring before the first occurence of }.
Now, Concat() this substring with your required string, and } at the end.
Try:
UPDATE table
SET params = CONCAT(
SUBSTRING_INDEX(params, '}', 1),
', "slider_fullscreen_button_skin": "myTheme", "slider_zoompanel_skin": "myTheme"',
'}'
)
WHERE params NOT LIKE '%myTheme%';

MySQL: SQL to insert rows using a string of ids

I need to insert ~150 simple rows (an id, and a static status of 'discard'). I have a string of the ids:
'123', '234r', '345', '456xyz'...
What's the simplest way to insert rows using this string of ids?
It seems like maybe there's some way to split the string on commas and... create a temp table to ...? I don't know - it just seems like this is the kind of thing that MySQL often manages to pull off in some cool, expedient way.
An example how to do create an INSERT statement with a few lines of PHP:
<?php
// copy your string of ids into this variable
$input = "'123', '234r', '345', '456xyz'";
// modify next line to get your desired filename
$filename = 'insert.sql'
// modify next line to your table name
$insert_statement = "INSERT INTO your_table_name (id, status) VALUES \n" .
'(' . implode(", 'discard')\n(", explode(', ', $input)) . ", 'discard');\n";
file_put_contents($filename, $insert_statement);
?>
Note
This is for this special use case. If the string of ids contains some special characters like single quotes, then this simple approach will fail.
The one way is to create CSV file with appropriate records and upload it at once to mysql.
Please follow this tutorial: http://www.mysqltutorial.org/import-csv-file-mysql-table/

MySQL query to append key:value to JSON string

My table has a column with a JSON string that has nested objects (so a simple REPLACE function cannot solve this problem) . For example like this: {'name':'bob', 'blob': {'foo':'bar'}, 'age': 12}. What is the easiest query to append a value to the end of the JSON string? So for the example, I want the end result to look like this: {'name':'bob', 'blob': {'foo':'bar'}, 'age': 12, 'gender': 'male'} The solution should be generic enough to work for any JSON values.
What about this
UPDATE table SET table_field1 = CONCAT(table_field1,' This will be added.');
EDIT:
I personally would have done the manipulation with a language like PHP before inserting it. Much easier. Anyway, Ok is this what you want? This should work providing your json format that is being added is in the format {'key':'value'}
UPDATE table
SET col = CONCAT_WS(",", SUBSTRING(col, 1, CHAR_LENGTH(col) - 1),SUBSTRING('newjson', 2));
I think you can use REPLACE function to achieve this
UPDATE table
SET column = REPLACE(column, '{\'name\':\'bob\', \'blob\': {\'foo\':\'bar\'}, \'age\': 12}', '{\'name\':\'bob\', \'blob\': {\'foo\':\'bar\'}, \'age\': 12, \'gender\': \'male\'}')
Take care to properly escape all quotes inside json
Upon you request of nested json, i think you can just remove last character of the string with SUBSTRING function and then append whatever you need with CONCAT
UPDATE table
SET column = CONCAT(SUBSTRING(column, 0, -1), 'newjsontoappend')
modify Jack's answer. Works perfectly even column value is empty on first update.
update table
set column_name = case when column_name is null or column_name =''
then "{'foo':'bar'}"
else CONCAT_WS(",", SUBSTRING(column_name, 1, CHAR_LENGTH(column_name) - 1),SUBSTRING("{'foo':'bar'}", 2))
end

Incrementing numerical value and changing string in SQL

I have a database that has stored values in a complicated, serialized array where one component is a string and another is the length of the characters of the string, in this format:
s:8:"test.com"
Where "s" holds the character length of the string in the quotations.
I would like to change the string from "test.com" to "testt.com", and I'm using the following statement in SQL:
UPDATE table SET row=(REPLACE (row, 'test.com','testt.com'))
However, this breaks the script in question, because it doesn't update the character length in the "s" preceding the string where "test.com" is stored.
I was wondering if there is a query I can use that would replace the string, and then also increment the value of this "s" preceding to where the replacement occurs, something like this:
UPDATE table SET row=(REPLACE (row, 's:' number 'test.com','s:' number+1 'testt.com'))
Does anyone know if this kind of query is even possible?
UPDATE table set row = concat('s:',length('testt.com'),':"testt.com"');
If you need to change exact string, then use exact query -
UPDATE table SET row = 's:9:"testt.com"' WHERE row = 's:8:"test.com"';
The string is a "serialized string".
If there are multiple strings to be replaced, it might be easier to create a script to handle this.
In PHP, it goes something like this:
$searchfor = serialize('test.com');
$replaceby = serialize('testt.com');
// strip last semicolon from serialized string
$searchfor = trim($searchfor,';');
$replaceby = trim($replaceby,';');
$query = "UPDATE table SET field = '$replaceby' WHERE field = '$searchfor';";
This way, you can create an exact query string with what you need.
Do fill in the proper code for db connection if necessary.

Change image name and update into same table using mysql query

I want to change image name in table like below.
image name : test.png
replace with : test_E.png
I want _E at end of all image name in table using mysql query.
Use replace function
update <table>
set image=replace(image,'.png','_E.png')
you could use this, if the image extension is not same in the table
update <table>
set image=concat(substring(image,1,locate('.',image)-1),'_E',
substring(image,locate('.',image),lenght(image)))
You can use string functions of MySQL query:
UPDATE TABLE SET IMAGE_NAME = CONCAT(SUBSTR(IMAGE_NAME,(CHAR_LENGTH(IMAGE_NAME) - 4)),
'_E' , SUBSTR(IMAGE_NAME, -4)) WHERE ID = <put record id>;
SUBSTR(IMAGE_NAME,(CHAR_LENGTH(IMAGE_NAME)-4)) would return name of file - assuming extension is of 3 chars. For 'test.png' above function would remove '.png' and function would return 'test'
SUBSTR(IMAGE_NAME, -4) would return last four chars of string - so 'test.png' would return '.png'
using concat you can concat 'test', '_E' and '.png' - returning 'test_E.png'
Please refer to string functions reference of MySQL for further use
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html