129

Can JavaScript connect with MySQL? If so, how?

6
  • 1
    no, unless you're not talking about about the JavaScript in the browser. Jun 11, 2010 at 11:02
  • 3
    What about server side JavaScript (e.g. through Rhino) ? can we connect to a database ?
    – Joand
    Sep 20, 2012 at 19:22
  • 10
    Or Node.js will work as well Oct 24, 2012 at 21:11
  • 4
    Ignore all the answers on this page because they are all wrong. In fact, it can be done. See developer.chrome.com/apps/app_network
    – Pacerier
    Aug 18, 2016 at 20:00
  • 1
    The accepted answer is just plain wrong (and was in 2010, too). This answer is correct. Dec 23, 2017 at 8:56

16 Answers 16

96

Client-side JavaScript cannot access MySQL without some kind of bridge. But the above bold statements that JavaScript is just a client-side language are incorrect -- JavaScript can run client-side and server-side, as with Node.js.

Node.js can access MySQL through something like https://github.com/sidorares/node-mysql2

You might also develop something using Socket.IO

Did you mean to ask whether a client-side JS app can access MySQL? I am not sure if such libraries exist, but they are possible.

EDIT: Since writing, we now have MySQL Cluster:

The MySQL Cluster JavaScript Driver for Node.js is just what it sounds like it is – it’s a connector that can be called directly from your JavaScript code to read and write your data. As it accesses the data nodes directly, there is no extra latency from passing through a MySQL Server and need to convert from JavaScript code//objects into SQL operations. If for some reason, you’d prefer it to pass through a MySQL Server (for example if you’re storing tables in InnoDB) then that can be configured.

0
60

If you want to connect to a MySQL database using JavaScript, you can use Node.js and a library called mysql. You can create queries, and get results as an array of registers. If you want to try it, you can use my project generator to create a backend and choose MySQL as the database to connect. Then, just expose your new REST API or GraphQL endpoint to your front and start working with your MySQL database.


OLD ANSWER LEFT BY NOSTALGIA

THEN

As I understand the question and correct me if I am wrong, it refers to the classic server model with JavaScript only on the client-side. In this classic model, with LAMP servers (Linux, Apache, MySQL, PHP) the language in contact with the database was PHP, so to request data to the database you need to write PHP scripts and echo the returning data to the client. Basically, the distribution of the languages according to physical machines was:

  1. Server Side: PHP and MySQL.
  2. Client Side: HTML/CSS and JavaScript.

This answered to an MVC model (Model, View, Controller) where we had the following functionality:

  1. MODEL: The model is what deals with the data, in this case, the PHP scripts that manage variables or that access data stored, in this case in our MySQL database and send it as JSON data to the client.
  2. VIEW: The view is what we see and it should be completely independent of the model. It just needs to show the data contained in the model, but it shouldn't have relevant data on it. In this case, the view uses HTML and CSS. HTML to create the basic structure of the view, and CSS to give the shape to this basic structure.
  3. CONTROLLER: The controller is the interface between our model and our view. In this case, the language used is JavaScript and it takes the data the model send us as a JSON package and put it inside the containers that offer the HTML structure. The way the controller interacts with the model is by using AJAX. We use GET and POST methods to call PHP scripts on the server-side and to catch the returned data from the server.

For the controller, we have really interesting tools like jQuery, as "low-level" library to control the HTML structure (DOM), and then new, more high-level ones as Knockout.js that allow us to create observers that connect different DOM elements updating them when events occur. There is also Angular.js by Google that works in a similar way, but seems to be a complete environment. To help you to choose among them, here you have two excellent analyses of the two tools: Knockout vs. Angular.js and Knockout.js vs. Angular.js. I am still reading. Hope they help you.

NOW

In modern servers based in Node.js, we use JavaScript for everything. Node.js is a JavaScript environment with many libraries that work with Google V8, Chrome JavaScript engine. The way we work with these new servers is:

  1. Node.js and Express: The mainframe where the server is built. We can create a server with a few lines of code or even use libraries like Express to make even easier to create the server. With Node.js and Express, we will manage the petitions to the server from the clients and will answer them with the appropriate pages.
  2. Jade: To create the pages we use a templating language, in this case, Jade, that allow us to write web pages as we were writing HTML but with differences (it take a little time but is easy to learn). Then, in the code of the server to answer the client's petitions, we just need to render the Jade code into a "real" HTML code.
  3. Stylus: Similar to Jade but for CSS. In this case, we use a middleware function to convert the stylus file into a real CSS file for our page.

Then we have a lot of packages we can install using the NPM (Node.js package manager) and use them directly in our Node.js server just requiring it (for those of you that want to learn Node.js, try this beginner tutorial for an overview). And among these packages, you have some of them to access databases. Using this you can use JavaScript on the server-side to access My SQL databases.

But the best you can do if you are going to work with Node.js is to use the new NoSQL databases like MongoDB, based on JSON files. Instead of storing tables like MySQL, it stores the data in JSON structures, so you can put different data inside each structure like long numeric vectors instead of creating huge tables for the size of the biggest one.

I hope this brief explanation becomes useful to you, and if you want to learn more about this, here you have some resources you can use:

  • Egghead: This site is full of great short tutorials about JavaScript and its environment. It worths a try. And the make discounts from time to time.
  • Code School: With a free and very interesting course about Chrome Developer tools to help you to test the client-side.
  • Codecademy: With free courses about HTML, CSS, JavaScript, jQuery, and PHP that you can follow with online examples.
  • 10gen Education: With everything you need to know about MongoDB in tutorials for different languages.
  • W3Schools: This one has tutorials about all this and you can use it as a reference place because it has a lot of shortcode examples really useful.
  • Udacity: A place with free video courses about different subjects with a few interesting ones about web development and my preferred, an amazing WebGL course for 3D graphics with JavaScript.

I hope it helps you to start.

Have fun!

4
  • Nice detailed answer explaining the mechanics.
    – Duane
    Jun 23, 2017 at 12:05
  • Thanks :) I have just added an update to the end of the answer to solve the problem. You can use a node server with a library called "mysql", and I have added a link to an API generator I have created that you can use to start a new API project. Hope it helps.
    – Timbergus
    Jun 25, 2017 at 17:07
  • Re "then": JavaScript used server-side goes back to 1995, when it was included in the Netscape Enterprise Server. Microsoft put "JScript" in its IIS server soon thereafter. JavaScript on the server is not, remotely, new. Dec 23, 2017 at 8:59
  • I think it would be good if this answer had the newest info at the top or just delete the old outdated info. It's also a bit verbose and focuses on particular languages. The short answer is that JavaScript can be used to connect to a MySQL database directly from Node.JS (or other server-side runtime environment) but not from the browser due to deliberate browser security.
    – Caltor
    Feb 21, 2020 at 22:01
28

No, JavaScript can not directly connect to MySQL. But you can mix JS with PHP to do so.

JavaScript is a client-side language and your MySQL database is going to be running on a server

6
  • 96
    small note: the fact that JavaScript runs on the client-side has NOTHING to do with the fact that it can't connect to a Database Server. It could be very well (though, highly unlikely) that a future version of the language would add APIs to access remote databases. Jun 1, 2011 at 14:36
  • 4
    I wouldn't call that "mix JS with PHP", though. What you might do is let PHP Code generate JavaScript Code/Data(json, e.g.) that it has retrieved from MySQL in advance. Or you might use PHP on a server to provide an http(json/REST/SOAP/... whatever) interface to access data that the php code retrieves from MySQL - and this http interface can be called by JavaScript code running anywhere, mainly a brwoser. As of today, also saying JavaScript is client side isn't current anymore - check Node.js for example.
    – Henning
    Sep 2, 2012 at 15:36
  • 15
    "JavaScript is a client-side language" Not necessarily: no more so than Java. Oct 10, 2012 at 10:34
  • 2
    with new version of mysql 5.7 httpclient can communicate directly with mysql database using http plugin(built for mysql 5.7) Oct 24, 2014 at 0:59
  • 1
    Why limit the answer to PHP? Any server-side language will do, including JavaScript when executed by Node.js runtime.
    – Caltor
    Feb 21, 2020 at 21:56
11

Bit late but recently I have found out that MySql 5.7 got http plugin throuh which user can directly connect to mysql now.

Look for Http Client for mysql 5.7

8

I think you would need to add something like PHP into the equation. PHP to interact with the database and then you could make AJAX calls with Javascript.

8

Simple answer is: no.

JavaScript is a client-side language that runs in the browser (node.js notwithstanding) and MySQL is a server-side technology that runs on the server.

That means you typically use a server-side language like ASP.NET or PHP to connect to the database.

1
  • 1
    Javascript (in the client-side, browser form) is used every day to connect with server-side technologies (Apache, Nginx, PHP, NodeJS, etc) running on the server. The very definition of server/client requires that the "divide" between them be surmountable.
    – jeteon
    Sep 22, 2015 at 9:25
7

YES? Have a look a meteor. Links:

http://meteor.com/screencast and http://net.tutsplus.com/tutorials/javascript-ajax/whats-this-meteor-thing/

I don't understand how it is done. But Nettuts+ put this thing in the javascript-ajax section, maybe magic happens.

It also shows some way to connect and insert to MongoDB with JS, like this:

Products.insert({Name : "Hammer", Price : 4.50, InStock : true});
Products.insert({Name : "Wrench", Price : 2.70, InStock : true});
Products.insert({Name : "Screw Driver", Price : 3.00, InStock : false});
Products.insert({Name : "Drill", Price : 5.25, InStock : true});
2
  • 1
    "You can substitute another database for MongoDB by providing a server-side database driver and/or a client-side cache that implements an alternative API. The mongo-livedata is a good starting point for such a project." -- docs.meteor.com Oct 10, 2012 at 10:52
  • Meteor was written using Node.js so I'm afraid this answer doesn't add anything new or change things. You just have a framework that covers client and server.
    – Caltor
    Feb 21, 2020 at 21:46
6

Yes. There is an HTTP plugin for MySQL.

http://blog.ulf-wendel.de/2014/mysql-5-7-http-plugin-mysql/

I'm just googling about it now, which led me to this stackoverflow question. You should be able to AJAX a MySQL database now or in the near future (they claim it's not ready for production).

5

Depending on your environment, you could use Rhino to do this, see Rhino website. This gives you access to all of the Java libraries from within JavaScript.

2

You can send AJAX requests to some server-side RESTful wrappers for MySQL, such as DBSlayer, PhpRestSQL or AlsoSQL (for Drizzle, a fork of MySQL).

2

Yes you can. MySQL connectors use TCP for connection, and in JS there is an little modified version of TCP client called Websocket. But you can't directly connect to MySQL server with websocket. You will need some 3rd party bridge between websocket and mysql. It receive query from websocket, send it to mysql, response result and resend to JS.

And this is my example bridge written in C# with websocket-sharp library:

class JSQLBridge : WebSocketBehavior
{
    MySqlConnection conn;

    protected override void OnMessage(MessageEventArgs e)
    {
        if (conn == null)
        {
            try
            {
                conn = new MySqlConnection(e.Data);
                conn.Open();
            }
            catch (Exception exc)
            {
                Send(exc.Message);
            }
        }
        else
        {
            try
            {
                MySqlCommand cmd = new MySqlCommand(e.Data, conn);
                cmd.ExecuteNonQuery();
                Send("success");
            }
            catch (Exception exc)
            {
                Send(exc.Message);
            }
        }
    }

    protected override void OnClose(CloseEventArgs e)
    {
        if (conn != null)
            conn.Close();
    }
}

JS side:

var ws = new WebSocket("ws://localhost/");

ws.send("server=localhost;user=root;database=mydb;");

ws.send("select * from users");
2

JavaScript can't connect directly to DB to get needed data but you can use AJAX. To make easy AJAX request to server you can use jQuery JS framework http://jquery.com. Here is a small example

JS:

jQuery.ajax({
type: "GET",
dataType: "json",
url: '/ajax/usergroups/filters.php',
data: "controller=" + controller + "&view=" + view,
success: function(json)
{
    alert(json.first);
    alert(json.second);
});

PHP:

$out = array(); 

// mysql connection and select query
$conn = new mysqli($servername, $username, $password, $dbname);


try {
  die("Connection failed: " . $conn->connect_error);

  $sql = "SELECT * FROM [table_name] WHERE condition = [conditions]";
  $result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    $out[] = [
       'field1' => $row["field1"],
       'field2' => $row["field2"]
    ];
  }
} else {
  echo "0 results";
}

} catch(Exception $e) {
  echo "Error: " . $e->getMessage();
}
    echo json_encode($out);
2
  • 1
    where is the MySQL query in this example?
    – Michael
    Feb 7, 2015 at 5:58
  • @Michael: Great question. Jan 18, 2017 at 17:45
1

No.

You need to write a wrapper in PHP, and then export the returned data (probably as Json). NEVER, get from your "_GET" the SQL code, as this is called an SQL injection (people who learn this will have full control over your database).

This is an example I wrote:

function getJsonData()
{
        global $db;
        if (!$db->isConnected()) {
               return "Not connected";
        }
        $db->query("SELECT * FROM entries");
        $values = array();
        while( $v = $db->fetchAssoc()){
                $values[] = $v;
        }
        return json_encode($values);    
}

switch (@$_GET["cmd"]){
        case 'data':
                print getJsonData();
                exit;

        default:
                print getMainScreen();
                exit; 
}

Do learn about SQL injections please.

1

You can connect to MySQL from Javascript through a JAVA applet. The JAVA applet would embed the JDBC driver for MySQL that will allow you to connect to MySQL.

Remember that if you want to connect to a remote MySQL server (other than the one you downloaded the applet from) you will need to ask users to grant extended permissions to applet. By default, applet can only connect to the server they are downloaded from.

1

If you're not locked on MySQL you can switch to PostgreSQL. It supports JavaScript procedures (PL/V8) inside the database. It is very fast and powerful. Checkout this post.

1

Of course you can. In Nodejs you can connect server side JavaScript with MySQL using MySQL driver. Nodejs-MySQL

Not the answer you're looking for? Browse other questions tagged or ask your own question.