user3304007 user3304007 - 3 months ago 10
MySQL Question

Mysql add value (concat) at the beginning, not at the end?

Ok so when user like a comment, my script adds user name to comments table, likes row.

$ben = "Rose,";

mysql_query("UPDATE comments set likes = CONCAT(comments.likes,
'".$ben."') WHERE id ='".$id."'") or die(mysql_error());


However, it adds at the end of the list. For example if likes row have these;

John,Mark,Mary,

after it adds, its

John,Mark,Mary,Rose,

But I want it to add to the beginning, like

Rose,John,Mark,Mary,

How can I do that ?

Answer

change arguments order function_concat

mysql_query("UPDATE comments set likes = CONCAT( 
'".$ben."',comments.likes) WHERE id ='".$id."'") or die(mysql_error()); 

With PDO:

use \PDO as PDO;
$PDO = new PDO('mysql:...');
$Stm = $PDO->prepare("UPDATE comments set likes = CONCAT(?,comments.likes) WHERE id =?");
$Stm->execute([$ben,$id]);