如何在php mysql中更新数据?

Let's say I want to update a message row without deleting the previous message. For example: row message has the current value "hello", now I want to add "hi" without replacing the word "hello". So the result should be "hello hi".

I've tried the code below but it won't work:

$text="hi";

$sql = "UPDATE class SET message= message+'$text' WHERE id=2";

or

$sql = "UPDATE class SET message= 'message'.'$text' WHERE id=2";

sorry, im not really good at english. thanks for the help

you can do use the mysql's concat() function to append data to a field:

$sql = "update class set message = concat(ifnull(message,"")," ".'$text') where id=2";

You may also want to consider a space before appending the new content!

Well, you should first of all you should really learn about SQL injection (and how to prevent it, including Prepared Statements).

You can do this in SQL using the CONCAT() function:

$sql = "UPDATE class SET message = CONCAT(message, '$text') WHERE id=2";

Try CONCAT instead, in your mysql query.

$text = "hi";
$myQuery = "UPDATE class SET message= CONCAT(message,'".$text."') WHERE id=2";

You should use the CONCAT function which is used to concatenate strings. Here since you are using the content of a php variable, it is good to escape the php variable from mysql query like '".$text."';

Have a look at the CONCAT() Function of MySql:

$sql = "UPDATE class SET message=CONCAT(message, '".$text."') WHERE id=2";

should do the trick.

You could try this:

$sql = "UPDATE class SET message=CONCAT(message, '$text') WHERE id='2'";

However, be aware that this is vulnerable to SQL Injections