Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing a MySQL query with node.js and node-mysql

I'm coming from a mostly PHP / MySQL background, and dabbing into node.js to create a blogging system for my own testing and for learning how to do things. The issue I'm having here is that I can't seem to figure out how to do a proper query. I've checked the docs for node-mysql but haven't been able to find out much about doing queries.

If I do var posts = rows[0]; I get the array of the the table and it looks good, but I'm trying to pass the specific fields to variables, but when I do the code below, I get a bunch of "unspecified"'s. I know there's something wrong here, and I would normally do a mysql_fetch_array in PHP, but I don't know the method for doing this in node.js and node-mysql.

connection.query('SELECT * FROM posts ORDER BY date', function(err, rows, fields) {
  if (err) throw (err);

  var post_date = rows[1];
  var post_author = rows[2];
  var post_content = rows[3];

  console.log('Date: ', post_date);
  console.log('Author: ', post_author);
  console.log('Content: ', post_content);
});
like image 315
Keith Avatar asked Feb 18 '23 05:02

Keith


1 Answers

rows actually contains the data rows and each row is an object that contains all fields for that row. So you should iterate over the rows and get the fields for each row like this:

for (var i = 0; i < rows.length; i++) {
    console.log('Date: ', rows[i].date);
}
like image 119
Niek Schmoller Avatar answered Feb 22 '23 13:02

Niek Schmoller