最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Performing a MySQL query with node.js and node-mysql - Stack Overflow

programmeradmin1浏览0评论

I'm ing 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);
});

I'm ing 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);
});
Share Improve this question edited Mar 12, 2013 at 16:41 loganfsmyth 162k31 gold badges346 silver badges258 bronze badges asked Mar 12, 2013 at 16:08 KeithKeith 1342 silver badges9 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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);
}
发布评论

评论列表(0)

  1. 暂无评论