skip to Main Content

I have database in mysql & have maintain 3 columns i.e. ID , name, slug.

Slug column is same as name but here I put combination of name column. Suppose if name is Micky Mehta then in slug I want it should show micky-mehta. In slug I want everything in small letters & if space then it should be replaced with dash. All this because I want SEO friendly url for my site. Now I can do this with program when new products gets added but is it also possible If I can directly do that with mySQL? I mean is there any function in mySQL which perform this kind of task?

3

Answers


  1. Try This
    example-

    UPDATE yourTable SET yourColumn = LOWER(replace('Your Value', ' ', '_')) 
    
    Login or Signup to reply.
  2. You can update data to fit your scheme:

    UPDATE mytable SET slug = REPLACE(LOWER(name), ' ', '-');
    

    If you want it to happen automatically every time you add a new row or update an existing row, you can use triggers:

    CREATE TRIGGER SetSlugIns BEFORE INSERT ON mytable
      FOR EACH ROW
      SET NEW.slug = REPLACE(LOWER(NEW.name), ' ', '-');
    
    CREATE TRIGGER SetSlugUpd BEFORE UPDATE ON mytable
      FOR EACH ROW
      SET NEW.slug = REPLACE(LOWER(NEW.name), ' ', '-');
    

    In MySQL 5.7, they now have generated columns, so you can do the same thing without writing triggers:

    CREATE TABLE mytable (
      id INT PRIMARY KEY,
      name VARCHAR(100),
      slug VARCHAR(100) AS (REPLACE(LOWER(name), ' ', '-')
    );
    
    Login or Signup to reply.
  3. You can also do this with your programming language. If you are coding in php you can do it as below
    Take a new variable say $slug

    $name='Jone Doe'; //the name value you getting from form or input
    
    //convert string into lower. It will give you 'jon doe'
    $nameInLower = strtolower($name); 
    
    // now replace space with hyphen.
    $slug=str_replace(' ', '-',$nameInLower);
    

    Insert the $slug variable in your database table along with the name column(considering id is auto incremented column.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search