-2

I am trying to update a table product_desc and there are two columns name and description. I have a standard text for desc: 'Buy $name from us'.

Now, I can simple write update query but I want to use the $name from product_desc.name field.

Is this possible by writing just the query?

UPDATE product_desc 
  SET description = "Buy $name from blah blah" 
  WHERE $name = product_desc.name where id > 0;

something like this.

ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
newbie756
  • 45
  • 1
  • 2
  • 8
  • 1
    Can you show the table's structure? also, concatenating data to a query is dangerous, use prepared statements instead. [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1) – Spoody Jul 23 '18 at 18:33

1 Answers1

1

you should use AND for more condition

UPDATE product_desc 
SET description = concat("Buy ", :name, "  from blah blah" )
where $name = product_desc.name 
AND id > 0; 

anyway you should use a proper data binding and not use php var in sql code ..

UPDATE product_desc 
SET description = "Buy $name from blah blah" 
where :name = product_desc.name 
AND id > 0; 

see for you db driver for use correct binding

or as suggested by Patrick Q if youn just need add the product name to description

UPDATE product_desc 
SET description = concat("Buy ", name  , " from blah blah" )
; 
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
  • 2
    The way I read it, OP actually wants to use the value from the `name` column as part of the description. No variables or binding needed, just a concat on the fixed-text and the column reference. – Patrick Q Jul 23 '18 at 18:36
  • missing paren .. add. – ScaisEdge Jul 23 '18 at 18:41
  • @scaisEdge I have MariaDB and it says unexpected character near :name – newbie756 Jul 23 '18 at 18:43
  • you must use a proper binging and not use the code with :name direcly .. anyway check you the 3th suggestion is for your need too – ScaisEdge Jul 23 '18 at 18:44
  • @scaisEdge tried this. It executes but nothing happens. – newbie756 Jul 23 '18 at 18:48
  • are you sure you have id > 0 and you have a valid content in name column?..answer updated without where .. – ScaisEdge Jul 23 '18 at 18:58
  • @scaisEdge yes I even tried id = 4 a specific one but it executes without updating – newbie756 Jul 23 '18 at 18:59
  • have you a valid name .. and how is long the description column? .. anyway check better .. if the query is executed the column must be updated .. at lest with "Buy from blah blah" – ScaisEdge Jul 23 '18 at 19:00
  • @newbie756 What is the response from your db when you execute this command? And how are you executing it? Command line? Through a PHP script? A tool like PHPMyAdmin or MySQL Workbench? – Patrick Q Jul 23 '18 at 19:02
  • @PatrickQ This one worked UPDATE product_desc SET description = concat("Buy ", name , " from blah blah" ) where id = 7; – newbie756 Jul 23 '18 at 19:14