使用MySQL数据库数据从for循环创建数组

时间:2019-05-03 14:37:18

标签: javascript mysql arrays

我正在尝试使用Javascript创建脚本,该脚本从MySQL数据库中获取数据,以便使用该数据创建一个数组,但是在尝试使Javascript连接到数据库时遇到了麻烦。

这是我的JS代码:

var mysql = require('mysql');

var con = mysql.createConnection({
    host: "*DELETED*",
    user: "*DELETED*",
    password: "*DELETED*",
    database: "*DELETED*"
});

// Array approach
var config = {
        container: "#collapsable-example",

        animateOnInit: true,

        node: {
            collapsable: true
        },
        animation: {
            nodeAnimation: "easeOutBounce",
            nodeSpeed: 700,
            connectorsAnimation: "bounce",
            connectorsSpeed: 700
        }
    };


    var array = [];

for (var i = 0; i <= con.query("SELECT MAX (id_dim) FROM dim"); i++) {

    var nome = con.query("SELECT itempt_dim FROM dim WHERE id_dim = " + i);
    var parente = "parent: " + con.query("Select itempt_dim from dim, rdim Where iddim_rdim = " + i);
    var nomeEscrito = "text: " + con.query("SELECT itempt_dim FROM dim WHERE id_dim = " + i);
    //var droplevel = "childrenDropLevel: " +
    //var pseudo = "pseudo: " +
    //var imagem = "image: " +
    array.push(nome = {
        parente,
        nomeEscrito
    });

}

console.log(array);

chart_config = [config, Sharan, Sharan2];

,我收到以下错误消息:

ReferenceError: require is not defined

EDIT1:所以我在PHP文件中使用了JS并尝试了以下操作:

<?php
      require('common/db.php');
    ?>

    <script type="text/javascript">

      // Array approach
      var config = {
              container: "#collapsable-example",

              animateOnInit: true,

              node: {
                  collapsable: true
              },
              animation: {
                  nodeAnimation: "easeOutBounce",
                  nodeSpeed: 700,
                  connectorsAnimation: "bounce",
                  connectorsSpeed: 700
              }
          };


          var array = [];
          var maxID = "<?php $con->query('SELECT MAX(id_dim) FROM dim'); ?>"

          for (var i = 1; i <= maxID ; i++) {

            var nome = "<?php $con->query('SELECT itempt_dim FROM dim WHERE id_dim = " + i + "'); ?>";
            var parente = "parent: " + " <?php $con->query('SELECT itempt_dim FROM dim, rdim WHERE iddim_rdim = " + i + "'); ?>";
            var nomeEscrito = "text: " + "<?php $con->query('SELECT itempt_dim FROM dim WHERE id_dim = " + i + "'); ?>";
            //var droplevel = "childrenDropLevel: " +
            //var pseudo = "pseudo: " +
            //var imagem = "image: " +
            array.push(nome = {
              parente,
              nomeEscrito
            });

          }

          console.log(document.write(array));

          chart_config = [config, Sharan, Sharan2];


    </script>

    <script>
        tree = new Treant( chart_config );
    </script>

0 个答案:

没有答案