SQL UPDATE event not functioning properly when triggered by Discord.js via message event

I've been grappling over the past few days to successfully implement an SQL UPDATE event in discord.js using the mysql npm package. I have meticulously checked all login details, table names, and column names, but still can't get it to work as intended. The goal is to increment an integer each time a message is sent in a Discord text channel.

Despite trying various approaches for the UPDATE event, none seem to be yielding the desired results.

Take a look at these snapshot logs: - (Before/After the event trigger) - (discord.js console output when a message is sent)

bot.on("message", message => {
    if (message.channel.type === 'dm') return;
    if (message.author.bot) return;
    if (message.content.startsWith(".")) return;

    connection.query(`SELECT * FROM logs WHERE id = '${message.author.id}'`, function (err, resultLogs) {
        if(err) throw err;
        let sql;

        if(resultLogs[0]) {
            console.log(resultLogs[0].msgcount);
            let newMessageCount = resultLogs[0].msgcount++;
            sql = `UPDATE logs SET msgcount = ${newMessageCount} WHERE id=${message.author.id}`;
            connection.query(sql, console.log);
        }
    });  
});

The expected behavior is that the integer should increment by one every time a message is sent.

Answer №1

If you want to increase the msgcount using a MySQL operator, you can do so directly without the need for a select query. It's important to remember to escape the value in your SQL statement to prevent any potential injections.

By the way, I have optimized and refactored your code:

bot.on('message', message => {
    if ( message.channel.type === 'dm' || message.author.bot || message.content.startsWith(".") ) return;

    connection.query('UPDATE logs SET msgcount = msgcount + 1 WHERE id = ?', [message.author.id], (error,  result) => {
      if (error) throw error;
      
      console.log(result);
    })
}

Answer №2

I haven't had experience with discord JS, but it seems like your code logic is correct to me. However, there are some parts that strike me as odd :

sql = `UPDATE logs SET msgcount = ${newMessageCount} WHERE id=${message.author.id}`
        connection.query(sql, console.log)

Why aren't there semicolons at the end of each line in this part?

Also, I'm not entirely sure about how the ` symbol works with strings, but have you double-checked if the SQL query is accurate (specifically if the message count and id values are properly replacing the variables)? It might be helpful to print it out to see.

(You used apostrophes for the 'select' query)

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

What steps can be taken to prevent Sequelizer from accidentally dropping a database?

After experimenting with Sequelizer, I noticed that the database is dropped every time the application is launched. How can I ensure that the database persists across different instances of the app? ...

React Typescript: exploring the power of dynamic types

Can dynamic typing be implemented? The JSON structure I am working with looks like this: { "fieldName": "Some text", "type": String, "inputType": "text" }, { "fieldName": "Some bool&q ...

Scraping dynamic content with Python for websites using JavaScript-generated elements

Seeking assistance in using Python3 to fetch the Bibtex citation produced by . The URLs follow a predictable pattern, enabling the script to determine the URL without requiring interaction with the webpage. Attempts have been made using Selenium, bs4, amon ...

Canceling request and SQL query in Yii2

Once the page has finished loading, I initiate an AJAX request to a specific action. However, if while waiting for a response from this action (which typically takes 2 or 3 seconds), the user clicks on another link, I need to be able to cancel the previou ...

During the installation of a package, npm encountered a require stack error with the code MODULE_NOT_FOUND

Whenever I attempt to install something using the npm install command, it throws an error saying "require stack" and "code MODULE_NOT_FOUND" C:\Users\dell>npm audit fix node:internal/modules/cjs/loader:1075 const err = new Error(message); ...

What exactly does a module's scope entail in browsers and Node.js environments?

Can someone clarify the scope of a module in different environments like browsers and Node? I'm particularly interested in whether a module-level variable is initialized once for the entire application or multiple times. Is each import creating a new ...

Apply the style when the page loads and remove it when clicked

There is a feature in my code that adds a class when an element with the class .tab is clicked. $(function() { $(".tab").click(function() { $(this).addClass('blueback'); $(".tab").not($(this)).removeClass('bl ...

Sluggish MySQL UPDATE operation

I'm dealing with a mysql table that has 400,000 rows and I've noticed that when I run a PHP script to update one row, it's taking around 3-4 seconds. This is causing some performance issues for me. Wondering if there are any ways to optimiz ...

Error occurred when attempting to submit form data to MySQL database

I am facing an issue with my form submission. I have created a form to insert values into a MySQL database, but when I click the submit button, the database is not getting updated. I'm not sure where I went wrong in my code. <html> <head> ...

npm run build command fails to compile, even though the development version is operational

I am facing an issue with my React app that was created using create-react-app. When I try to compile a production build using npm run build, it fails and throws the following error: $ npm run build > [email protected] build C:\Users\Use ...

Send the text of the element to an AngularJS controller

Currently, I am attempting to extract the text inside a <p> element within my Angular application and pass it on to both a method and a view using ng-route. The objective is that when a user clicks on the <p>, the innerText will be sent through ...

Is there a way I can set a variable as global in a jade template?

I am trying to pass a global object to a jade template so that I can use it for various purposes later on. For instance: app.get("/", function(req, res){ var options = { myGlobal : {// This is the object I want to be global "prop ...

Unable to display canvas background image upon webpage loading

Currently working on a JavaScript project to create a captcha display on a canvas. The issue I'm facing is that the background image does not load when the page initially opens. However, upon hitting the refresh button, it functions as intended. Here& ...

"Utilizing Google Tag Manager to trigger events and push them to the data layer

My goal with this code is to trigger an event in the data layer through Google Tag Manager whenever a user hovers over a specific area on the website for at least 1 second. The challenge I'm facing is that I have 8 other areas on the site using the sa ...

It is not possible to utilize Vue.js to employ the <slot> feature for rendering the parent component

After attempting to implement the slot feature following the example on the Vue official site, I encountered a failure despite keeping my code very concise. Parent Component <template> <subMenuTemp> <div class="text" > paren ...

PHP Joomla 2.5 MySQL Import Data - Access Denied

I encountered an issue while attempting to import a CSV file into a table. A permission denied error occurred: Error importing CSV File: (1045) Access denied for user 'username'@'localhost' (using password: YES) SQL=LOAD DATA INFILE ...

Fixing MySql Issue: Deleting Duplicate Rows Based on Priority

Initial Information I have a table named Test: -- Table Creation CREATE TABLE Test( id integer, title varchar (100) ); -- Insertion INSERT INTO Test Values (1, "Hi"), (2, 'Hello'), (2, "Hellew"), ...

Error encountered when parsing JSON data in Vue.js due to presence of invalid characters in the

I have been working on a web application that allows me to upload a JSON file, make changes to it, and then download it. However, the resulting JSON is not valid because certain characters seem to change during the process. Even when I simply upload and do ...

The promise is only guaranteed to resolve correctly upon the refreshing of the page

Exploring an API that retrieves a list of Pokemon and related data, the code snippet below demonstrates how to achieve this. export function SomePage() { const [arr, setArray] = useState([]); useEffect(() => { fetchSomePokemon(); }, []); f ...

Creating a jQuery-based AJAX mechanism for sending friend requests

Looking to create a friend request system similar to Facebook using MySQL, PHP, jQuery AJAX, and JSON. I have the JSON results ready, but need assistance with the jQuery part. Can anyone help? Below are the sample JSON results: If there's an error: ...