Can JavaScript connect with MySQL? If so, how?
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.
Of course you can. In Nodejs you can connect server side JavaScript with MySQL using MySQL driver. Nodejs-MySQL
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).
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.
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.
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);