1

For example, I have a registration form and I also have a button for submitting the details, so once I click the button, I want them to be sent to the mysql database. Unfortunately, I only know how to do db queries on the server.js but how do I do it on any script? Below is the way that won't work

 $("button#submit").click(function () {
    var username = $('#usr').val();
    var password = $('#pwd').val();

    db.query("INSERT OR REPLACE INTO user_data (username, password) VALUES (" + username + "," + password + ")");
    //// something like this
 })
2
  • The code you have shown above seems to operate in a browser environment, not in Node.js. Your browser's environment does not know about your Node.js code. Commented Mar 23, 2017 at 8:17
  • Your query above is wide open to SQL Injection attacks and errors. See: bobby-tables.com. Use parameterized queries. Commented Mar 23, 2017 at 8:19

1 Answer 1

1

You can't run queries on a mySql database from the frontend. That would be a huge security issue. You'll have to send the values back to your backend and query the database from there, with the values.

Also make sure to use prepared statements. Your query is wide open to mysql injections.

enter image description here

You can run a prepared statement using node-mysql with mysql.format():

var sql = "SELECT * FROM ?? WHERE ?? = ?";
var inserts = ['users', 'id', userId];
sql = mysql.format(sql, inserts);

Translated for your query, this would be

let query = "REPLACE INTO user_data (username, password) VALUES (?,?)";
let inserts = [username, password]; // however you obtain them in the backend
mysql.query(mysql.format(query, inserts));

Note that I changed INSERT OR REPLACE to REPLACE, as it was a syntax error.

Sign up to request clarification or add additional context in comments.

6 Comments

You'll need to make an ajax call from the frontend to a route on your server with the data. Here's a example stackoverflow.com/questions/19015897/jquery-ajax-simple-call
I understand, but how do I tell the server.js what query to do. for example: $('button#submit').click(function(){ /// send that prepared statement to the server } ); and then execute it on server?
Nothing(!!!!) related to mysql happens on the frontend. You send an ajax request with username and password as the data, then do everything mysql related on the backend
Thanks @T.J.Crowder I'll grab the comic - little bobby tables is such a nice guy :D
So what do I do after I am done with the ajax call?. Sorry if the question is stupid but I am still a bit new to this
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.