I want to write a MySQL select statement in javascript. Is it possible? Most I found were for .asp, to be embedded into a .php
Thanks Jean
-
1yes, it's possible but t-o-t-a-l-l-y uselessYour Common Sense– Your Common Sense2010年11月28日 20:40:13 +00:00Commented Nov 28, 2010 at 20:40
-
@col if it works then I'd useX10nD– X10nD2010年11月28日 20:42:37 +00:00Commented Nov 28, 2010 at 20:42
-
Usually JavaScript code is executed on the client-side and the MySQL engine runs on the server side...xgMz– xgMz2010年11月28日 20:45:34 +00:00Commented Nov 28, 2010 at 20:45
-
3No! Really, you shouldn't be doing this, it would be a big security hole, as users would be able to execute arbitrary SQL!spolto– spolto2010年11月28日 20:49:20 +00:00Commented Nov 28, 2010 at 20:49
-
@Spolto arbitrary SQL might not be a problem if the user that is running the query has limited privileges.Rolf– Rolf2011年04月15日 22:48:26 +00:00Commented Apr 15, 2011 at 22:48
4 Answers 4
With a PHP server, JavaScript runs on the client and MySQL runs on the server. The only way for this to work would be for the JavaScript to send the query to the PHP server to be run, and the results returned to the browser. This is extremely insecure since destructive queries can be crafted by a malicious client, and you are advised not to do this. Instead pass the criteria you want to look for, and let the PHP handle generating the query.
3 Comments
The SQL should be generated on the server by the PHP code. Only the parameters should be sent from the Javascript.
You could in theory generate SQL in Javascript on the web client and then send it to the server to be executed but this would most likely create a huge security hole in your application.
Comments
The other problem with writing sql queries on the client in javascript is that you still have to send them to the server to actually execute them against the mysql server. There is no way to directly query a mysql server from the browser without activeX or Java or similar and/or exposing your mysql server to the internet.
As the others have mentioned, this is a really bad road to go down.
I would challenge why you would like to do this in javascript in the first place? Why is Javascript your first choice? What problem does javascript solve for you that server-side script (php or whatever) doesn't?
Comments
Here is a MySQL client written in JavaScript, but it runs server-side using node.js:
https://github.com/felixge/node-mysql
Not exactly what you're asking for but might be useful. node.js is an interesting technology.
You can also send MySQL queries to the server and then have a PHP (for example) script run them there and return the results. If you do that make sure to secure your database and run them as a user with restricted permissions so that your database will not be vandalized or your application hacked.