views:

251

answers:

6

Can JavaScript connect with MySQL? If so, how?

+2  A: 

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

falkon
Thanks, how would I do so?
Anonymous the Great
+1  A: 

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.

Kerry Peterson
+2  A: 

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.

Dean Harding
Thanks alot! :]
Anonymous the Great
+2  A: 

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.

elcuco
A: 

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 tp://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(); 
$out['first']   = 'first value';
$out['second']   = 'second value';
echo json_encode($out);
Octan
+1  A: 

You can connect to MySQL from Javscript 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.

Rajiv