Update table field by replacing a string value with a new one

Posted on August 28, 2008, Filled under PHP,  Bookmark it

Thanks for visiting our website! We regularly publish posts like this one. If you are interested in receiving the latest updates as soon as they are posted, please consider subscribing to the RSS feed or to our e-mail newsletter.

Greetings,

Let’s suppose you have a mysql database and you need to update only a part of a field’s value, not all.

This can be done using the following query:

UPDATE `table` SET `field` = REPLACE(`field`, "old_string", "new_string");

Here’s how it will look like in a PHP Code:

<?php
$db_host = 'db_host'; // usually localhost
$db_user = 'db_username';
$db_pass = 'db_password';
$db_name = 'db_name';

$db = mysql_connect($db_host, $db_user, $db_pass)
or die ("Unable to connect to Database Server.");

mysql_select_db ($db_name, $db) or die ("Could not select database.");

$table_name = 'lists';

$table_field_name = 'category';

$initial_string = 'man';
$new_string = 'boy';

$query = "UPDATE `".$table_name."`
SET `".$table_field_name."`=REPLACE(`".$table_field_name."`,
'".$initial_string."', '".$new_string."');";

/* NOTE: You can add conditions to this query in case you want to update
a specific field ID like this:

UPDATE `table_name`
SET `field_name` = REPLACE(`field_name` "old_string", "new_string")
where field_id='id_number_here';
*/

$sql_query = mysql_query($query) or die(mysql_error());

if($sql_query)
{
echo 'Table ' .$table_field_name. ' has been successfully updated.';
}
?>

Feel free to post any comments regarding this tutorial.

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

Sponsors

Related Posts

Leave a Reply


* = required fields

(will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


  

CommentLuv Enabled