Executing MySQL query with node.js and node-mysql

I proceed from the main background of PHP / MySQL and go into node.js to create a blogging system for my own testing and learn how to do it. The problem I am facing here is that I cannot figure out how to make the right request. I checked the docs for node-mysql but couldn't learn much about query execution.

If I do var posts = rows[0]; , I get an array of the table, and it looks good, but I try to pass certain fields to variables, but when I do the code below, I get a bunch of "unspecified" "'s. I know that something is wrong here, and I usually did mysql_fetch_array in PHP, but I don’t know a method for 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); }); 
+4
source share
1 answer

rows actually contains rows of data, and each row is an object that contains all the fields for that row. Therefore, you should iterate over the rows and get the fields for each row as follows:

 for (var i = 0; i < rows.length; i++) { console.log('Date: ', rows[i].date); } 
+7
source

Source: https://habr.com/ru/post/1468750/


All Articles