Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2006
    Posts
    4,832
    Tokens
    0

    Latest Awards:

    Default [PHP] How would I go about doing this?

    Hi,

    I have a table with 20,000 odd rows. Every row has a 'title', such as "hello there" or "my name is bob", as an example. What I want to do is to grab these titles, put a dash ( - ) between the spaces and then insert these titles with dashes into the table under 'dashed'.

    So for example, I have these under title:

    hello there mate
    how are you
    its cool yeah
    fun fun fun
    food tastes good
    lets get some cola
    good idea mate

    And then the PHP script does what I said above and turns them into...

    hello-there-mate
    how-are-you
    its-cool-yeah
    fun-fun-fun
    food-tastes-good
    lets-get-some-cola
    good-idea-mate

    I'm not great at PHP but I imagine explode would be used? Any help?

    Thanks!

  2. #2
    Join Date
    Apr 2010
    Location
    Newcastle
    Posts
    655
    Tokens
    50

    Default

    Either using a loop in PHP (untested):
    PHP Code:
    <?php
    /* Assuming you've already connected to the DB */

    // Get rows
    $query=mysql_query("SELECT * FROM `items`;");
    while(
    $row=@mysql_fetch_array($query)){
         
    $newTitle=str_replace(" ","-",$row['title']); // Generate new title
         
    mysql_query("UPDATE `items` SET `dashed`='{$newTitle}' WHERE `title`='".mysql_real_escape_string($row['title'])."';"); // Query the database
    }
    echo 
    "All done.";
    ?>
    Or a much more efficient, all-in-one query method (untested):

    PHP Code:
    <?php
    /* Already connected */
    mysql_query("UPDATE `items` SET `dashed`=REPLACE(`title`,' ','-');");
    ?>
    Last edited by Apolva; 01-07-2010 at 09:53 PM.

  3. #3
    Join Date
    Jun 2006
    Posts
    4,832
    Tokens
    0

    Latest Awards:

    Default

    Quote Originally Posted by Apolva View Post
    Either using a loop in PHP (untested):
    PHP Code:
    <?php
    /* Assuming you've already connected to the DB */

    // Get rows
    $query=mysql_query("SELECT * FROM `items`;");
    while(
    $row=@mysql_fetch_array($query)){
         
    $newTitle=str_replace(" ","-",$row['title']); // Generate new title
         
    mysql_query("UPDATE `items` SET `dashed`='{$newTitle}' WHERE `title`='".mysql_real_escape_string($row['title'])."';"); // Query the database
    }
    echo 
    "All done.";
    ?>
    Or a much more efficient, all-in-one query method (untested):

    PHP Code:
    <?php
    /* Already connected */
    mysql_query("UPDATE `items` SET `dashed`=REPLACE(`title`,' ','-');");
    ?>
    I ******* LOVE YOU MAN! The second one worked, didn't try the first 'cos the second looks easier! Damn that looks so simple! Ta!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •