0

I have constructed a variable containing the SQL statement in my client-side

var sql = "SELECT * FROM restaurant WHERE (areaCategory" + " " + area + ")" + "AND (cuisineCategory" + " " + cuisine + ") AND (priceCategory" + " " + price +")"

How can I export this SQL statement from client-side to server-side in order to do send this statement? The SQL statement varies depending on situations, hence I have to create a variable.

smartdroid
  • 312
  • 2
  • 10
mbdx
  • 1
  • 3
  • 3
    Warning: for security reasons you probably don't want to do this; it would be safer to construct the query on the server and only send the parameters (e.g. area, cuisine, etc) from the client. – Alex Jan 27 '21 at 07:08
  • That is a good idea, how can I send or export the parameters from the client to the server? – mbdx Jan 27 '21 at 07:10
  • @Daryl You can use Axios to send parameters from browser to server. https://www.npmjs.com/package/axios – Ozgur Sar Jan 27 '21 at 07:14
  • or fetch. Any http client will do!! – Harry Kruger Jan 27 '21 at 07:14
  • @Daryl there are several ways, depending on how your application is set up. One relatively simple way is to set up an HTTP endpoint on your server, which you then send a request to from the client. I would start by googling: "ajax request" – Alex Jan 27 '21 at 07:15

1 Answers1

2

Well, as mentioned by @Aley, You really don't want a client to have full access to your database!

Instead I would send the params to the server using an AJAX call or a form, then use prepared statements on server side

AJAX

You might want to use a library like axios and make a Ajax call with post method:

//client side
axios.post('/restaurant', {
    area: areaCategory,
    cuisine: cuisineCategory
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Forms

Forms should be self-explanatory

<!--client side-->
<form method="post" action=/restaurant">

<input type="text" name="area" placeholde="Area…">
<input type="text" name="cuisine" placeholde="Cuisine……">
<input type="submit">
</form>

Prepared statements

As there are many different databases with different interfaces, here are some links:

Does SQLite3 have prepared statements in Node.js?

Preventing SQL injection in Node.js

How do I create a prepared statement in Node.JS for MSSQL?

MoPaMo
  • 517
  • 6
  • 24
  • Am I right to say that I post it into the server-side script? – mbdx Jan 27 '21 at 07:39
  • I am using a dropdown option form, any idea how to "submit" since I am not using a submit button? is there such thing as onchange="submit"? – mbdx Jan 27 '21 at 07:42
  • You can just leave the summit button out and the form will be submitted when the user hits enter – MoPaMo Jan 27 '21 at 08:35