0

This is my client side snippet:

    var stuff = 'this: ';
    connection.query("SELECT * FROM users", function (err, results) {
        stuff += results;
    });
    io.sockets.emit('numrows', 'rows length is ' + stuff);

This is my server side snippet:

<b id = 'test'></b>
<script>
  socket.on('numrows', function(data) {
    document.getElementById('test').innerHTML = data;
  });
</script>

The HTML gets changed to 'rows length is this: ', meaning that the function fails to return the number of rows. What am I missing?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Randomdude
  • 101
  • 2
  • 9
  • Put the `io.sockets.emit()` call inside the callback function. – Barmar Jul 10 '18 at 19:12
  • And why are you expecting it to return the row count? `results` is a 2-dimensional array of all the information in the `users` table. If you want the row count, use `results.length`. – Barmar Jul 10 '18 at 19:13
  • Neither of these solutions worked. Adding .length still returns an empty variable. When I put it in the callback function, the socket message was not emitted at all - it seems that the function does not activate whatsoever. – Randomdude Jul 10 '18 at 19:21
  • What does `console.log(results.length)` show? – Barmar Jul 10 '18 at 19:23
  • Absolutely nothing! It seems that the function does not activate at all. – Randomdude Jul 10 '18 at 19:23
  • What about `console.log(err)`? – Barmar Jul 10 '18 at 19:24
  • Still nothing! Logging into the console outside the query, naturally, outputs as expected. Anything inside the function simply does not execute at all. – Randomdude Jul 10 '18 at 19:25
  • 1
    If you do an update or insert query, does the database get changed? – Barmar Jul 10 '18 at 19:27
  • No. I do not have a database manager for node.js, so I was using that method to check whether the queries work at all. When I started xampp and changed the port inside node.js's connection to mysql to xampp's database's port, the function seems to work as expected and I can see my database updating in phpmyadmin. However, when I change the port to my node.js server's port, it ceases to work. I do not want to develop on node.js with apache on just for mysql, but I also don't want to use mongoDB... I know this deviates from the question, but what would you recommend in this situation? – Randomdude Jul 10 '18 at 19:30
  • Sorry, I don't use node.js, so I can't really advise. – Barmar Jul 10 '18 at 19:32

0 Answers0