Update Table in SQL via PHP

Discussion in 'PHP' started by JosS, Aug 7, 2007.

  1. #1
    I have a table called "names"

    Via PHP can I scan and turn everything in the names table of the database to

    lowercase, and remove all whitespace.
     
    JosS, Aug 7, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Hi again. :D

    
    mysql_query("UPDATE names SET name = LOWER(REPLACE(name, ' ', ''))") OR die(mysql_error());
    
    PHP:
    "name" should be the field name where you want to make these changes.

    EDIT:

    I highly suggest making a backup of the data before running such code. (You never know)
     
    nico_swd, Aug 7, 2007 IP
    JosS likes this.
  3. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #3
    You would want to select all of the records in the database, loop through them all, and update each one after you modified it with php.

    As long as the database isn't terribly large, php shouldn't have much problem doing it.

    Use strtolower to make everything lowercase, and use preg_replace to remove all whitespace, or trim() to just remove whitespace from the begining and the end.

    Here's a quick sample flow for the php.

    
    
    $getRecords = mysql_query("SELECT columns FROM table");
    
    while($array = mysql_fetch_array($getRecords)){
    
    $newValue = trim(strtolower($array['originalValue']));
    
    //or 
    
    $newValue = preg_replace('/\s/','',strtolower($array['originalValue']));
    
    
    mysql_query("Update table Values (new values to be inserted here) Where id = 'id of this row'");
    
    }
    
    
    PHP:
     
    jestep, Aug 7, 2007 IP