Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add to existing value in mysql column using CONCAT function?

trying to add text to an existing value in mysql using mysql's concat function?

so existing value is currently 'john' and after function has run will be 'johnewvalue'

i am trying to add a piece of text ':reply' to the existing text which is in my subject column in my database ptb_messages.

i am trying to do this using mysql's concat function but im not getting any result what so ever.

$sql = mysql_query("UPDATE ptb_messages SET subject = CONCAT subject, 'newvalue' WHERE id='".$message_id."'"); 

can someone please show me a way of getting it to do what i want. thanks.

like image 725
Nick James Avatar asked Feb 11 '13 15:02

Nick James


People also ask

How can I add value in one column in MySQL?

In syntax, First, you must specify the name of the table. After that, in parenthesis, you must specify the column name of the table, and columns must be separated by a comma. The values that you want to insert must be inside the parenthesis, and it must be followed by the VALUES clause.

How can I append a string to an existing field in MySQL?

To prepend a string to a column value in MySQL, we can use the function CONCAT. The CONCAT function can be used with UPDATE statement.

Which MySQL function can be used to add text to an existing value?

Which MySQL function can be used to add text to an existing value? We can append a string of data to an existing data of a field by using concat function of MySQL.

Does concat work in MySQL?

CONCAT() function in MySQL is used to concatenating the given arguments. It may have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string.


1 Answers

it should be

UPDATE ptb_messages 
SET subject = CONCAT( subject, 'newvalue')
WHERE ... 
  • MySQL CONCAT

in PHP

$sql = mysql_query("UPDATE ptb_messages SET subject = CONCAT(subject, 'newvalue') WHERE id='".$message_id."'"); 

As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

  • How to prevent SQL injection in PHP?
like image 124
John Woo Avatar answered Nov 06 '22 19:11

John Woo