I need a MySQL query (if PHP is required you can use that too) that will delete the ending of all the values on one column named 'url'.
The problem is that I saved the urls having the .php
and now I want to delete that ending from all the values in the database.
Example:
old values:
my_url.php
my_sadas.php
new values:
my_url
my_sadas
Below is the syntax for the SUBSTRING() function to delete the last N characters from the field. Syntax: SELECT SUBSTRING(column_name,1,length(column_name)-N) FROM table_name; Example: Delete the last 2 characters from the FIRSTNAME column from the geeksforgeeks table.
It could be this using the SUBSTR function in MySQL: SELECT `name` FROM `students` WHERE `marks` > 75 ORDER BY SUBSTR(`name`, -3), ID ASC; SUBSTR(name, -3) will select the last three characters in the name column of the student table.
Remove characters from string using TRIM() TRIM() function is used to remove any character/ whitespace from the start/ end or both from a string.
MySQL TRIM() Function The TRIM() function removes leading and trailing spaces from a string.
UPDATE mytable
SET myfield = SUBSTRING(myfield, 1, LENGTH(myfield)-4) ;
If you want to also check whether the field ends with '.php'
before truncating, you can add this condition:
UPDATE mytable
SET myfield = SUBSTRING(myfield, 1, LENGTH(myfield)-4)
WHERE RIGHT(myfield, 4) = '.php' ;
Oh, there's also LEFT()
which can be used instead of SUBSTRING()
as well
And CHAR_LENGTH()
should be used instead of LENGTH()
as it is multi-byte safe (while LENGTH()
is not):
UPDATE mytable
SET myfield = LEFT(myfield, CHAR_LENGTH(myfield)-4)
WHERE RIGHT(myfield, 4) = '.php' ;
UPDATE files
SET fileName = SUBSTRING(fileName, 1 , (LENGTH(fileName) - 4)) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With