Node.js mysql connection only works while executed with command prompt - javascript

I am still new to node.js so I apologize in advance if this question is silly.
First I have tried to execute the test.js with command prompt
conn.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'tgs'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
test.js
function testconnect()
{
var conn = require('./conn');
var sql = "INSERT INTO chat_line (line_text) VALUES ('test')";
conn.query(sql, function (err, result) {
if (err) throw err;
});
}
testconnect();
in the command prompt
D:\xampp\htdocs\TGS\>node test.js
and it works, I did get the input in my database. After that I wanted to try to implement this in my system so I have tried to execute this in php
testing.php
<script>
function testalert()
{
alert("alert1");
var conn = require('./conn');
var sql = "INSERT INTO chat_line (line_text) VALUES ('test')";
conn.query(sql, function (err, result) {
if (err) throw err;
});
alert("alert2");
}
</script>
<input type="button" onclick="testalert();">
and it doesn't work. The first alert did pop up after clicking the button but the second alert did not, also there is no input in my database.

Node.js and PHP are different technologies, you cannot directly use one in another if you want to interact with one another you will need some mediator like (API, queue, database etc).
try to understand how nodeJs works, there is a dependency of mysql library at line one, which is a middleware helping with dealing with database
var mysql = require('mysql');
above line can only work in nodeJs environment, if you want to use it in PHP then there will be some other library in PHP to do same (I am not PHP guy so cannot help with ideal one here) and you will not need nodeJS at all with your example.
do let me know if I made it clear.

Related

why is var mysql = require('mysql'); returning undefined

EDITED:
I am working on a page that takes the information a user enters into a form and adds it to a database. I created the database with mysql. When trying to connect to my database using javascript. My code breaks on var mysql = require('mysql');:
I realized that this may be due to either the code being ran in a function or having the DOM related code in the function...
I tried running a simple version of the code without those elements and it works to connect to and update the database but I need to be able to pull the values from the form so I am still struggling with how to do this.
function saveUserForm() {
var firstName = document.getElementById("firstName");
var lastName = document.getElementById("lastName");
var psw = document.getElementById("psw");
var userName = document.getElementById("userName");
var email = document.getElementById("inputText");
alert('test');
var mysql = require('mysql');
alert("mysql test");
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "abc123",
database: "PBSC_Parking_DB"
});
con.connect(function(err) {
if (err){
throw err;
alert("error");
}
var sql = "INSERT INTO accounts (UserName, FirstName, LastName, Email, UserPassword) VALUES ('"+userName+ "', '"+firstName+"','"+lastName+"','"+email+"','"+psw+"')";
con.query(sql, function (err, result) {
if (err) {
throw err;
alert("test error");
}
alert("account added");
console.log(result.affectedRows + " record(s) updated");
});
});
}
you can try writing npm i mysql in the built in terminal of your ide instead of cmd and check that the mysql folder is added to your project dependencies
or you can run npm i --g mysql to install that globally
require('mysql') is async, so it needs to be treated as a promise. For safety, I would load this outside of the function scope. The only time you would need to require something inside the scope of a function is for lazy loading local assets.
You try to include a library with node from cmd so that's normal to give you undefined.
cause node declares values like this. so you seem to install MySQL with npm globally. so it appears with you.
that's not related to your code at all.
you need to produce bug in your code via log error or debug code!

how should I apply sync node.js module with mysql, socket functions?

I'm trying to understand and use sync-npm module, but not sure how to change my functions below to match sync format... (https://www.npmjs.com/package/sync)
Basically I'm trying to use input data (which is formed as a list in client side) I receive from frontend(client) and send it to node.js via socket. I tried to store it in my global variable 'query', but I learned that it doesn't get updated. So when I tried to print 'query' outside of socket function, it doesn't work.
It sounds like I should use sync module, but I'm not quite sure how to implement that in my code...If anyone could give me an idea how to change my functions below, it would be great..thanks!
Receiving input data from frontend and sending it to node.js via socket
var server = app.listen(3001);
var socket = require('socket.io');
var io = socket(server);
var query = []
// Register a callback function to run when we have connection
io.sockets.on('connection',newConnection);
function newConnection(socket){
console.log('new connection: ' + socket.id);
socket.on('search', newSearch);
function newSearch(final){
query.push(final)
console.log(query[0]);
console.log(Array.isArray(query[0])); //returns True
console.log(query[0][0]); // this also works
console.log(query[0][1]);
}
}
console.log('print');
console.log(query);
// this only gets printed in the beginning as an empty array
Ultimately, I'm parsing that list of input data and concat into my sql select phrase. Below is my DB portion code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '~~~',
user : '~~~',
password : '~~~',
database : '~~~'
});
connection.connect();
console.log('mysql connected');
var sql = 'select' + '*' + 'from EBN ';
//ideally data in the 'query' list will concat with this sql string
connection.query(sql,function(err,rows,fields){
if(err){
console.log(err);
}
else{
fs.writeFileSync('search.json', JSON.stringify(rows), 'utf8');
}
});
Firstly, you should wrap the code that does the query execution in a function, something like
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '~~~',
user : '~~~',
password : '~~~',
database : '~~~'
});
connection.connect();
console.log('mysql connected');
function executeQuery(query)
var sql = 'select' + '*' + 'from EBN ';
//do something with query and add it to the sql string
connection.query(sql,function(err,rows,fields){
if(err){
console.log(err);
}
else{
fs.writeFileSync('search.json', JSON.stringify(rows), 'utf8');
}
}
}
This is necessary because you don't want to execute a query right after starting the server, but only after you received the query message via socket. So now you can call executeQuery(final) in your socket message handler.
You should learn how asynchronous programming and callbacks works in nodejs/javascript, and why you should use it as much as possible for server applications (e.g. use fs.writeFile instead of writeFileSync). You can use packages like sync to make life easier for you, but only when you know exactly what you want to do. Just throwing something with the name 'sync' in it at a problem that might be caused by asynchronicity is not going to work.

function to search database for keywords

trying to get functionality to search a mysql database for keywords using javascript, running into problems with how to execute the commands in js and how to insert the keywords from an input box to the mysql query.
<html>
<head>
<title></title>
<script> function mysqlList(){
var keyword = document.getElementById('keyword').value;
var mysql = require('mysql');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'xxxxxx',
password : 'xxxxxx',
database : 'joblist',
}
);
connection.connect();
var queryString = 'SELECT name, trello FROM graduates WHERE (name LIKE '%keyword%' OR trello LIKE '%keyword%');
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
for (var i in rows) {
var console = console.log('name: ', rows[i].name, '|', 'trello: ', rows[i].trello);
}
});
connection.end();
};
window.console = {
log: function(str){
var node = document.createElement("div");
node.appendChild(document.createTextNode(str));
document.getElementById("myLog").appendChild(node);
}
}
</script>
</head>
<body onload="onload();">
<input type="text" name="enter" class="enter" value="" id="keyword"/>
<button onclick="mysqlList()">run query</button>
<p id="myLog"></p>
</body>
</html>
this is non functional at the moment, but even if anyone could point me in the direction of some good tutorials I would appreciate it.
thanks!
You can't do that.
First: require() is specific to NodeJS. It is not available in the browser. Some of the modules which can be loaded with it are available in the browser, but mysql is not.
Second, and related: You can't connect to a MySQL database directly from a web browser. Javascript running in a browser can only make HTTP connections to web servers, and even then only on a limited basis.
You need to implement an API on the server -- possibly using Node, possibly something else -- to perform a search. Then you can use the XMLHttpRequest browser API -- or something based on it, like $.ajax() in jQuery -- to call that API.

Javascript MySQL Connection on HTML Page

I'm using node.js's node-mysql driver for MySQL. I wrote this scrap of code
var mysql = require("mysql");
var connection = mysql.createConnection({
host : "localhost",
user : "root",
password : "",
database : "story"
});
function testQuery() {
connection.query("INSERT INTO stories (TITLE, AUTHOR, STORY) VALUES
(\"hello\",\"goodbye\",\"sayonara\")", function(err,rows){
if(err) throw err;
} )
return;
}
So when I run the code in the testQuery() function in the node.js command line and it works as expected inserting hello goodbye and sayonara into the mysql database. But when I place the script into a HTML page and have a button onclick run testQuery() I don't get any result.
You are trying to run Nodejs server code on the client, this will not work. Also this would mean you will become hacked instantly because your password is stored in encrypted, plain text and stored on the clients machine. Double no no. You must start a new node instance and serve this code from the server, not from the browser.

Using mysql node.js driver to get an entire database as JSON

I'm working on creating a JavaScript file to get a JSON dump of an entire MySQL database, running on server side. I found and am using the MySQL driver for node.js (https://www.npmjs.com/package/mysql) for queries, it's been straight forward enough to start. My issue is that I need to call multiple queries and get the results from all of them to put into a single JSON file and I can't quite get that to work. I'm entirely new to JavaScript (basically never touched it before now) so it's probably a relatively simple solution that I'm just missing.
Currently I do a query of 'SHOW TABLES' to get a list of all the tables (this can change so I can't just assume a constant list). I then just want to basically loop through the list and call 'SELECT * from table_name' for each table, combining the results as I go to get one big JSON. Unfortunately I haven't figured out how to get the code to finish all the queries before trying to combine them, thus retuning 'undefined' for all the results. Here is what I currently have:
var mysql = require('mysql');
var fs = require('fs');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass',
database: 'test_data'
});
connection.connect();
connection.query('SHOW TABLES;', function(err, results, fields)
{
if(err) throw err;
var name = fields[0].name;
var database_json = get_table(results[0][name]);
for (i = 1; i < results.length; i++)
{
var table_name = results[i][name];
var table_json = get_table(table_name);
database_json = database_table_json.concat(table_json);
}
fs.writeFile('test_data.json', JSON.stringify(database_json), function (err)
{
if (err) throw err;
});
connection.end();
});
function get_table(table_name)
{
connection.query('select * from ' + table_name + ';', function(err, results, fields) {
if(err) throw err;
return results;
});
}
This gets the table list and goes through all of it with no issue, and the information returned by the second query is correct if I just do a console.log(results) inside the query, but the for loop just keeps going before any query is completed and thus 'table_json' just ends up being 'undefined'. I really think this must be an easy solution (probably something with callbacks which I don't quite understand fully yet) but I keep stumbling.
Thanks for the help.
I'm guessing that this is for some sort of maintenance type function and not a piece that you need for your application. You're probably safe to do this asynchronously. This module is available here: https://github.com/caolan/async
You can also use Q promises, available here: https://github.com/kriskowal/q
This answer: describes both approaches pretty well: Simplest way to wait some asynchronous tasks complete, in Javascript?

Categories