Mahesh Singh Chouhan
Mahesh Singh Chouhan

Reputation: 2588

How to use mysql PDO query using nodeJs and express4

I am developing a application in express4 framework using mysql for database query but i am not sure about how to use mysql PDO query in nodeJs.

Upvotes: 2

Views: 8288

Answers (3)

fred727
fred727

Reputation: 2819

If you are looking for something similar to PDO in Node, you can try Sequelize.

Upvotes: 0

Sparw
Sparw

Reputation: 2743

If you want to simplify your requests, you can use mysql-json npm package.

This package implements basics methods with JSON data

// Query to mysql server 
mysqlJson.query(mysqlQuery, callback);

// Insert a new row with JSON data 
mysqlJson.insert(tableName, dataToInsert, callback);

// Update some row(s) matching with JSON conditions 
mysqlJson.update(tableName, data, conditions, callback);

// Delete some row(s) matching with JSON conditions 
mysqlJson.delete(tableName, conditions, callback);

Hope it helps :)

Upvotes: 1

Ian Mbae
Ian Mbae

Reputation: 146

Unfortunately as noted in an above comment, PDO is php specific and as of the time of writing this, I know not of a PDO equivalent in nodejs that gives you the full PDO feeling of SQL db agnostic power. ( You could however try knex.js at http://knexjs.org/)

If you on the other hand insist on using PDO, you will have to write your logic in php then run it from your nodejs instance.

You can interface with almost any language from another by running it in CGI (Common Gateway Interface) mode.

Luckily, there is a pretty neat and very easy to use module on npm that does just that for php.

The node-php cgi module. To install it, run

npm i --save node-php

Then in your express application,

var php = require("node-php");

var app = express();

app.use("/", php.cgi("/path/to/php_script_directory"));

app.listen(3000);

so if you have a php script test.php, run

http://your_ip_or_domain:your_port/your_script.php passing in your parameters as a GET request.

e.g. http://127.0.0.1:3000/test.php?message=Hello&sender=framify

You can place your php scripts that bear the PDO dependent logic in the specified directory and just run them comfortably from node.

index.php is the default so you do not have to specify it in the url path when making requests to it.

Needless to say, You can also use jQuery, Angular.$http ...) to make the http GET requests and acieve the same result.

Please note that POST , PUT , DELETE request methods will NOT work with this module (as at the time of my writing this).

ALSO NOTE

You need to install or enable php-cgi for the respective php version in your machine and the server that you run the code on.

For instance, I use Ubuntu Linux with php7

to install php-cgi, i will run :

sudo apt-get install php7.0-cgi 

I don't know much about windows, but I hope that the above example will give you a clue;

Upvotes: 1

Related Questions