<?php
$connect = mysqli_connect('localhost', "root", "", "test");
if(!$connect){
die(mysqli_connect_error());
}
$sql = "SELECT * FROM articles";
$result = mysqli_query($connect, $sql) or die(mysqli_connect_error());
while($row = mysqli_fetch_array($result)){ ?>
<div class='article-div'>;
<a href='articleviewer.php?id=$row[ID]' class='article-title'> . <?php $row['Title'] ?>. </a>;
</div>;
<?php }
mysqli_close($connect);
?>
So I have this code in PHP, which is self-explanatory really. It fetches the MySQL in an array and keeps printing divs for each article while posting the article's title.How do I do this in node.js with express? I have the "mysql" module installed. So what's the node equivalent to the mysqli_fetch_array()?
As npm's mysql module documentation says, you simply need to make a query like:
connection.query('SELECT * FROM `books` WHERE `author` = "David"', function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});
You can then iterate over results
via simple loop. Note: In the beginning of the documentation, there is an explanation about how to connect to the database and configure it. Read that first :)
You can use mysql or node-mysql modules:
npm install -g mysql
or
npm install -g node-mysql
Below is example usage (assuming there is a table named example_table
with columns ID
, FileName
and FileSize
in database node_dev
):
var mysql = require('mysql'),
qid = '1'; // example ID
var db = mysql.createConnection({
host : 'localhost',
user : 'DATABASE_USER_HERE',
password : 'DATABASE_PASSWORD_HERE',
database : 'node_dev'
});
/* SQL */
db.connect();
db.query('SELECT * FROM `example_table` WHERE RowID=?', [qid], function(err, rows, fields) {
if (err) {
throw err;
console.error(err);
} else {
for (var i = 0, len = rows.length; i < len; i++) {
// either of those two will do:
console.log(rows[i].FileName, rows[i].FileSize);
console.log(rows[i]['FileName'], rows[i]['FileSize']);
}
}
});
db.end();
/* SQL */
You'ill probably (most of the time) want to write simple middleware/microservices with other node modules such as express, http/https, Oauth2 which will monitor for requests, catch parameters and send some output parsed as JSON or something.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.