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!
- August 28, 2008
- article by Gabriel C.
- Leave a reply!
Sponsors
Related Posts
-
How to add a suffix to a field’s valueat August 30, 2008
-
How to add a prefix to a field’s valueat August 30, 2008 with 1 comment
-
How to replace multiple spaces from a string in PHPat August 29, 2008
-
Get maximum ID from a tableat August 30, 2008 with 1 comment
-
PHP: Sanitize Data to Prevent SQL Injection Attacksat January 9, 2009 with 6 comments
