PDA

View Full Version : [PHP] How would I go about doing this?



Hitman
01-07-2010, 09:25 PM
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!

Apolva
01-07-2010, 09:45 PM
Either using a loop in PHP (untested):


<?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
/* Already connected */
mysql_query("UPDATE `items` SET `dashed`=REPLACE(`title`,' ','-');");
?>

Hitman
01-07-2010, 10:07 PM
Either using a loop in PHP (untested):


<?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
/* 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!

Want to hide these adverts? Register an account for free!