javascriptdatabasecountoutputweb-sql

How to save WebSql COUNT output as javascript variable?


I am looking for suggestions on how to best complete this task, and have found nothing on the web. I am wanting to count the number of results that are returned from an SQL SELECT query and output that on my HTML page using JS/Jquery. Feel free to tell me there is a quicker and easier way than what I have done!!

I have found some suggestions using node.js, but I do not want to use that, as this is for a small school project.

This is the function that I am using when the select box is clicked. I am using it in conjunction with the 'onchange' in HTML (I think its HTML) and that works.

function placesLeft(val) {
    let time = document.getElementById("placesLeft");
    //time.innerHTML = val;
    let selected = val;

    db.transaction(function(tx) {
        tx.executeSql('SELECT COUNT ( * ) FROM Sessions WHERE sessiontime = (?)', [selected], function(x, results) {
            for (let i=0; i < 50; i++) {
                const u = results.rows.item(i);
                let count = 50 - i;
                console.log(count);
                console.log(i);
                console.log(u);
                time.innerHTML = count;
                console.log(time.innerHTML);
        };
        });
    });
}

Currently, it outputs the correct number of results when the query is run if I console.log 'u'. However, it outputs as this in the console: {COUNT ( * ): 2}. When I try and add it to the

tag I am using, it looks like this on the webpage:

[object, Object].

I am using WebSQL if you haven't realised, JS, and HTML. Fairly proficient in jQuery too, if that helps.

Here is a link to my code:

https://webucate.com.au/project/8sBxh4dPQ42fYB7viODZ/share

To get to the page I am talking about, click: book a session -> Scroll down to 'Choose a time' -> pick something. (10:00am and 1:00pm are the values I have in my database, and they appear 1 and 2 instances in the databases, respectively) In the console, you should see what u, I and count outputs.


Solution

  • The SQL Query uses a COUNT() function. It will return only one row and one column in the results.

    As such there is no need to iterate the result set. Is there a reason why you use an i-loop that iterates 50 times?

    I would suggest changing the SQL command to

    SELECT COUNT ( * ) AS COUNT FROM Sessions WHERE sessiontime = (?)
    

    So that the column name of the value you need will be set as COUNT.

    After that, retrieving the required value from the result set will be easier. You can simply get the first row with results.rows[0]. Then retrieve the value at the column "COUNT".

    var count = results.rows[0]["COUNT"]
    time.innerHTML = count;
    

    Hopefully this is solves your problem.