【问题标题】:How to Convert Query from PHP-MySQL to Node.js with Mysql and return value如何使用 Mysql 将查询从 PHP-MySQL 转换为 Node.js 并返回值
【发布时间】:2020-08-21 22:54:15
【问题描述】:

我想从mysql中选择数据并将值放入对象中。

它在 php 上工作,但我不明白为什么在 node.js 中不起作用

注意:我只放了部分代码。

php 中的我的代码:

$res = mysqli_query($mysqli, "SELECT message FROM mempool messageID=1");

$row = mysqli_fetch_assoc($res);

$test = new BlockChain();

$test->addBlock(new Block($row['message']));

node.js 中的代码

con.query("SELECT message FROM mempool where messageID=1", function (err, rows, fields) {
    if (err) throw err;
  });
let test = new Blockchain();
test.addBlock(rows);

node.js 的错误:

ReferenceError: rows is not defined

请帮忙?

【问题讨论】:

    标签: php mysql node.js object


    【解决方案1】:

    因为在 nodejs 中您使用回调函数,并且行变量未在范围之外定义。如果您将其更改为

    con.query("SELECT message FROM mempool where messageID=1", function (err, rows, fields) {
        if (err) throw err;
        console.log(rows);
        let test = new Blockchain();
        test.addBlock(rows);
        console.log(test);
      });
    

    您可以将其重写为异步/等待方式

    const rows = await db.query( 'SELECT message FROM mempool where messageID=1' );
    let test = new Blockchain();
    test.addBlock(rows);
    

    【讨论】:

      【解决方案2】:

      这个例子可能有用db select nodejs example

      问题是上面提到的行的范围应该在 con.query(....);

      【讨论】:

        猜你喜欢
        • 2014-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-24
        • 2020-05-22
        • 1970-01-01
        相关资源
        最近更新 更多