-3

I want to replace the string "?" with a different array values in the order using javascript

SELECT "x0"."NAME", "x0"."DOB", "x0"."SEX", "x0"."CATEGORY"
FROM "PERSON" "x0"
WHERE ((("x0"."NAME" <> ?) AND ("x0"."NAME" = ?)) AND ("x0"."NAME" < ?))
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
Ashok
  • 15
  • 5
  • 1
    Is this java or javascript? And also - what exactly are you trying to achieve? From afar, it looks as though you don't really need to replace the values, but to use a `PreparedStatement`. – Mureinik Jan 10 '16 at 17:57
  • 1
    Actually this is just straight up SQL. I hope he is not building a query through javascript and executes it against the db from the front end. – Mario Tacke Jan 10 '16 at 17:58
  • 2
    You are setting yourself up for a [SQL injection](http://www.w3schools.com/sql/sql_injection.asp) unless you are super careful. Please read about this and better solutions to your problem [here](https://stackoverflow.com/questions/15778572/preventing-sql-injection-in-node-js). – Johannes Jander Jan 10 '16 at 17:59
  • @Ashok, please consider marking your question as answered or editing its content to get more information! :) – Mario Tacke Jul 08 '16 at 17:24

1 Answers1

0

One possible solution is this:

var query = 'SELECT "x0"."NAME", "x0"."DOB", "x0"."SEX", "x0"."CATEGORY"' +
                    'FROM "PERSON" "x0"' +
                    'WHERE ((("x0"."NAME" <> ?) AND ("x0"."NAME" = ?)) AND 

("x0"."NAME" < ?))';

var names = ['borr', 'odin', 'thor'];

for (var i = 0; i < names.length; i++) {
    query = query.replace(/\?/, '"' + names[i] + '"');
}

console.log(query)

https://jsfiddle.net/0twfrdxz/

However, this will open up your application to SQL Injection. It would probably be better to give the query named parameters and generate the statement on the server after you sanitize the inputs. That being said, the above should work for testing.

Mario Tacke
  • 5,378
  • 3
  • 30
  • 49
  • Or use [a replacement function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter). – robertklep Jan 10 '16 at 21:31