1

Recently I did text-transform: capitalize in css where the first letter of each word is capitalized but the data in phpmyadmin is in lowercase. It will only be uppercase if I manually capitalize the letter. How can I fix it?

Dharman
  • 30,962
  • 25
  • 85
  • 135
North
  • 25
  • 6
  • You need to update your data [Using mysql](https://stackoverflow.com/questions/3278207/mysql-capitalize-first-letter-of-each-word-in-existing-table) or php [ucword](https://www.w3schools.com/php/phptryit.asp?filename=tryphp_func_string_ucwords) – angel.bonev Apr 27 '21 at 09:00
  • So there's no code that can fix this permanently? – North Apr 27 '21 at 09:05

1 Answers1

1

You can create a triggers on insert and update

CREATE TABLE Test(id INTEGER, title VARCHAR(255));    
DELIMITER $$
CREATE 
    TRIGGER ucwordOnTestInsert
    BEFORE insert
    ON Test
    FOR EACH ROW
    BEGIN
        SET NEW.title = initcap(NEW.title);
    END$$
CREATE 
    TRIGGER ucwordOnTestUpdate
    BEFORE update
    ON Test
    FOR EACH ROW
    BEGIN
        SET NEW.title = initcap(NEW.title);
    END$$
CREATE
    FUNCTION `initcap`(input VARCHAR(255))
    RETURNS VARCHAR(255)    
    BEGIN
    DECLARE len INT;
    DECLARE i INT;

    SET len   = CHAR_LENGTH(input);
    SET input = LOWER(input);
    SET i = 0;

    WHILE (i < len) DO
            IF (MID(input,i,1) = ' ' OR i = 0) THEN
                    IF (i < len) THEN
                            SET input = CONCAT(
                                    LEFT(input,i),
                                    UPPER(MID(input,i + 1,1)),
                                    RIGHT(input,len - i - 1)
                            );
                    END IF;
            END IF;
            SET i = i + 1;
    END WHILE;

    RETURN input;
    END$$

DELIMITER ;

insert into Test(id, title) values(1, "hello");
insert into Test(id, title) values(2, "hello world");
insert into Test(id, title) values(3, "hello World");
insert into Test(id, title) values(4, "hello World");
UPDATE `Test` SET title = 'this is a big test' WHERE `id` = 4;   
SELECT * FROM Test;

You can see it working demo here

If you need to update your old data just update all rows:

UPDATE `Test` SET title= title

You can read more for function initcap

angel.bonev
  • 2,154
  • 3
  • 20
  • 30
  • can i apply this code on existing table or do i have to create new table? sorry, MySQL noob here. – North Apr 28 '21 at 14:53
  • Yes you can apply triggers to existing table just change `ON Test` to `ON YourTableName` and `title` to the field that you use – angel.bonev Apr 29 '21 at 06:14
  • Hi @North if this or any answer has solved your question please consider [accepting it](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – angel.bonev May 13 '21 at 11:38