Javascript SQL query not returning the expected multiple rows, only returning one instead

I have a table containing multiple rows of test results, each row includes the ID of the test taker. Using the logged-in user information, I've added additional rows to the table to ensure accuracy. However, when printing the result to the console, only one result is displayed.

router.get('/tableResults',function(req, res, next) {
  console.log(req.session.passport.user);
  const db = require('./db_connection.js');
  var id = req.session.passport.user;

  db.query('SELECT * FROM testResults where id = ?',[id], function(error, results, fields) {  
    // Display results where user IDs match
    if(error) throw error;
    var results = results[0];

    console.log (" 1st " + results);

    var tableData = [ results]; 

    console.log (tableData);

    res.redirect('/home');
  });
});

// Error Result in Putty

Nodemon] starting `node ./bin/www`

24 

Connected!

 1st [object Object]

[ RowDataPacket {

test_id: 1,

username: 'rr',

gradeOne: 1,

gradeTwo: 7,

gradeThree: 0,

id: 24 } ]

GET /tableResults 302 169.552 ms - 54

24

true
GET /home 304 89.895 ms - -
GET /dist/css/bootstrap.min.css 404 10.086 ms - 3199

Answer №1

Make sure to set your 'results' with all results, not just the first one (result[0]).

It is also pointless to perform this action.

Consider trying it this way:

router.get('/tableResults',function(req, res, next) {
  console.log(req.session.passport.user);
  const db = require('./db_connection.js');
  var id = req.session.passport.user;

  db.query('SELECT * FROM testResults where id = ?',[id], function(error, results, fields) {  
    // Display results that match the user ids
    if(error) throw error;

    console.log ("1st: ", results[0]);
    console.log ('All: ', results);

    // You can iterate through 'results' with a for loop to display one row at a time if needed

    res.redirect('/home');
  });
});

Changes made:

1- Ensured 'results' contains all data instead of just the first entry (previous code was results = results[0])

2- Eliminated unnecessary var tableData as it duplicates the value of 'results'.

Answer №2

When handling the callback function for your query, you are given three parameters: error, results, and fields. Inside the callback function, you create a new variable named results and assign it the first item from the results parameter, which is results[0].

To access all the rows in the result without conflicting variable names, remove the line var results = results[0]; and loop through the entire array:

for(var i = 0; i < results.length; i++) {
  console.log(results[i]);
}

Avoid using repetitive variable names to prevent confusion. Understanding variable scope can be challenging; learn more about it here: What is the scope of variables in JavaScript?. To mitigate these issues, consider declaring use strict at the beginning of your code to enable Strict Mode.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transform a row into a clickable element

I am currently working on a social media platform where users can search for venues stored in the database. In my search.php file, I have implemented a text box that dynamically loads venue names from the database into a venuesearch div as the user types. ...

How can you notice when a DOM element is deleted from the page?

I am in the process of creating a custom directive that will ensure only one element is active at a time. Directive: displayOneAtATime Description: This directive can be applied to a DOM node to guarantee that only one element with this directive can be v ...

Troubleshoot the pattern of Pascal's Triangle

Can someone help me understand what's wrong with my implementation of Pascal's Triangle in JavaScript? I came across a similar thread discussing recursion, but I'm having trouble figuring out the errors in my code. I would appreciate fresh e ...

Step-by-step guide for implementing an "on change" event for a select box within a dialog box

I recently wrote an HTML code snippet like this: <div id = "dialog-1" title = "Dialog Title goes here..."> <select id= "lang" name= "lang"> <option value="1"> TEXT </option> <option value="2"> HTML </op ...

VueJS method for making an HTTP GET request

Attempting to make an http get request using Vue js. I can't seem to find any issues with the logic, although I'm not very experienced with vuejs. Continuously encountering these two errors: [Vue warn]: Error in mounted hook: "TypeError: Cann ...

Ways to implement the function provided in the website using javascript

Exploring the world of JavaScript functionality as a beginner, I am eager to try pasting dynamic data into HTML. I came across a helpful link providing instructions on how to achieve this using a table format. However, despite my best efforts, I am strugg ...

Firebase: Database and Storage - the art of efficiently linking images to posts | Vue.js

React Redux MongoDB I have developed a platform for users to share text and an image with their posts. Currently, I am assigning the complete URL of the image associated with each post using post.postPicture. This method is functional. The images are sav ...

Is it possible to iterate through HTML elements without relying on forEach()?

Currently working on my web-based system using Node.js and HTML. Are there any alternative ways to iterate through HTML elements without using forEach? I'm considering something like this (for example): <% for(var ctr=0; ctr<arrayname.length ...

Iterate through the array to import data into QlikView

In QlikView, I am importing data using the following script: / /Importing data from flat file dataimport: LOAD @1 AS CoCd, @2 AS Period, @3 AS [Doc. Date], @4 AS [Pstng Date], @5 AS TranslDate, @6 AS Reference, @7 AS DocumentNo, @8 AS Crcy, @9 ...

SQL Challenge: In terms of technicality, how many individuals transitioned from IBM to Google?

Imagine you have the following data set: id organization year_started 1 Apple 2001 1 IBM 2002 1 Oracle 2005 1 Microsoft 2010 2 IBM 2002 2 Microsoft 2004 2 Oracle 2008 Member 1 started at IBM in 2002, then moved to Oracle in 2005 and la ...

Selenium encountered an error when trying to execute the 'querySelector' function on the document. The selector provided, my_selector, is not recognized as a valid selector

Whenever I run this code: document.querySelector(my_selector) using selenium, an error is thrown: Failed to execute 'querySelector' on 'Document' my_selector is not a valid selector my_selector is definitely a valid selector that func ...

Error TS2307: Module '~express/lib/express' could not be located

Currently, I am in the process of converting a fully functional JavaScript file to TypeScript. Since I am using Express in this particular file, I made sure to include the following at the beginning of the file: ///<reference path="./typings/globals/n ...

Is it not possible to access the profile page using the GET method?

I am currently using Express.js to display user input in the URL after submitting a form and redirecting the user to their profile page with their name in the URL. To achieve this, I utilized req.query and the GET method. var express = require('expre ...

How can I retrieve the ultimate value of a JQuery UI Slider and store it in a PHP variable?

I am looking to add 2 JQ UI Sliders to a single page on my PHP website. I need to capture the final values from both sliders (the last value when the user stops sliding) and store them in PHP variables for multiplication. How can I accomplish this task? I ...

What is the best way to prevent a font awesome icon from appearing in a span during data loading

I am currently working on an Angular 11 application where I have implemented an icon to trigger the loading of a graph. However, I have noticed that there is a delay in loading the graph when the icon is clicked. To prevent users from triggering the icon m ...

What is the best way to retrieve shared columns from various tables in a Database?

Welcome to all the intelligent minds out there!! Recently, I encountered a unique SQL question during an interview. Question: If there are 100 tables in a Database and I want to retrieve common records from each table. For instance, let's say the l ...

Combining Various Items Retrieved from Fetch Request

I am attempting to merge multiple objects retrieved from an API by grouping them based on their id and values, ensuring that any modifications are only applied to individual objects rather than affecting all of them. Here is my latest approach: const car ...

Assigning the Style property to an element using a string that includes HTML tags

My HTML string is populated with elements such as button, li, span, and more. I am looking to add specific styles to buttons based on their class name. For example, if button.btn { some styles } and button.btn-success { some other styles } O ...

What is the best way to show a dropdown menu list using my code and JSON response object?

I am currently working on displaying a dropdown list based on the JSON response object. How can I implement it with the code snippet below? in HTML <select class="form-control" name="productCategories[]" id="productCategories< ...

How can I arrange a specific array position in Vuejs according to the Id value?

<div v-for="(item, index) in gr" :key="space.id" class="val-name"> </div> After making a few modifications to the API call logic, I was able to achieve my desired outcome. However, the issue lies in the fact that ...