Is there a SQL query glitch in JavaScript?

Although I am aware of the potential risks involved in connecting to a database using JavaScript, for this particular project, I have made an exception. The purpose of this project is unique and requires the use of JavaScript.

document.getElementsByClassName("option")[0].onclick = function() {
    event.preventDefault();
    var mysql = require('mysql');
    var con = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "",
        database: "dbname"
    });
    con.connect(function(err) {
        if (err) throw err;
        var email = document.getElementById("email").value;
        var password = document.getElementById("password").value;
        var sql = 'SELECT * FROM accounts WHERE email = ' + mysql.escape(email) + ' AND password = ' + mysql.escape(password);
        con.query(sql, function (err, result) {
            if (err) throw err;
            console.log(result);
        });
    });
}

While I have previously worked on a similar project using PHP, I am now exploring the same with JavaScript. However, there seems to be an issue at hand. My intention is to display the result in the console but instead, I am encountering the following:

https://i.sstatic.net/wqdt1.png

I do not claim to be an expert programmer - in reality, this project serves as a learning experience for me as a student. Any assistance or guidance would be greatly appreciated!

Answer №1

Remember to always include quotation marks when dealing with strings in SQL. Failure to do so may result in errors, such as neglecting to put quotes around the email and password fields.

It's recommended to use parameters instead of directly substituting variables into the SQL query, even if you take measures to escape them for safety.

var sql = 'SELECT * FROM accounts WHERE email = ? AND password = ?';
con.query(sql, [email, password], function (err, result) {
    if (err) throw err;
    console.log(result);
});

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

Is my design going overboard with dependency injection while constructing loosely connected JavaScript modules?

I am in the process of developing a section of my website that will utilize a moderate amount of JavaScript, and I am striving to write it in the most efficient way possible. I am transitioning from a mindset rooted in JS 2010 to one more aligned with 2016 ...

Validating email addresses and confirming their existence with the help of ko.observable

Currently, I am working on applying validations to emails to determine if they are valid or not using JavaScript. Additionally, I want to check in the database via AJAX to verify if the email already exists. The challenge I am facing is how to ensure the e ...

Different ways to change the value of a variable in an isolated scope using another directive

Utilizing a directive with two modes, edit and preview, multiple times in my codebase. function () { return { restrict: "E", scope : { model : '=' }, [...] controller : function($scope, $el ...

Is there a way to calculate the average of similar items within an array and combine them into a single object?

I currently have an array of objects structured like this: [ costBreakdown: { flexMeetAncCost: "1,274,051", flexOneTimeCosts: "0", flexSeatCharges: "2,403,869", tradFacilMgmtCost: "134,437", tradOneTimeTot ...

Issue with Next.js's notFound() function not properly setting the 404 HTTP Header

Our decision to use Nextjs was primarily driven by the need for SSR and SEO optimization. We rely on an external REST API to fetch data on the front end, but we face challenges when trying to pre-render certain pages and display a proper 404 Not Found head ...

Assign the colId to the pinnedBottomRowData property within Ag Grid

I'm facing an issue with displaying data in the pinned row within ag-Grid Vue 2. I am utilizing pinnedBottomRowData to supply data for the pinned row, but despite the pinned row being visible, it remains empty. The problem arises from using dot notati ...

React Native: Implementing scroll-based header animations in ScrollView

Currently, I am working on implementing an animated header with ScrollView on the screen. In this implementation, I need to set my view based on the Y position of the ScrollView during scrolling. This is how it's done: const onScroll = ({ nativeEvent: ...

What is the process for obtaining the hash of every hyperlink?

I'm currently working on implementing an active link state based on scroll position for each section. My goal is to extract the hash value from the link. The issue I'm facing is that when I run the line 'console.log($(this).eq(i).hash);&ap ...

Selecting a full table row activates a top-up popup

I have successfully implemented a script in Javascript to enable full table row selection as shown below. <script type="text/javascript"> $(function() { $('#link-table td:first-child').hide(); $('#link-table tr').hover(func ...

Develop an npm package that includes necessary dependencies

I am working on a distributed node.js project and I want to package the project's domain in a standalone file. To start, I created a package named "common" which contains some utilities by using the following command: npm pack This created the commo ...

Error: The property '_eventListeners' cannot be set on an undefined object

Encountering an error while running tests with React, Jest, and Enzyme - in need of assistance! ● Test suite failed to run TypeError: Cannot set property '_eventListeners' of undefined at Window.close (E:/TEST-UI/node_mo ...

Node.js (Express), passport.js, mongoose.js, and Android app all have in common the HTTP Error 307 - Temporary redirect

I am currently constructing a REST Api using Node.js (Express.js and Moongose.js). I have a single post route that takes JSON data and redirects it to the signup page (/app/signup) if the user is a first-time user (not found in the database), or to the log ...

"Deleting a database with a MongoDB / MongoLab Remove request successfully on a local environment, but accidentally removing

I am using nodejs, expressjs, and mongodb for this project. When the site is live, it utilizes mongolab. A POST request is sent from the front end to the server, where a single matching record in the database is deleted. The server-side code (written in Ex ...

Seeking assistance to integrate Dat-GUI with Meteor.js

I am attempting to incorporate Dat-GUI into my meteor project by adding the dat-GUI source in the client/lib folder. Below is my code snippet: Template.EditorControllbar.rendered = function () { var controllBar = document.getElementById('control ...

Upon page initialization, VueJS namespaced Vuex module getter does not properly return the expected value

Even in identical situations, I am receiving different outputs from the same getter function. console.log(store.getters); When checking the console, I see: {}: auth/loggedIn: true, which is the correct value. However, when specifically accessing this get ...

Sending an array via an AJAX POST request using jQuery

I'm having trouble with my POST function not passing the data[] array. Can someone confirm if my array is correct? Or perhaps there's something missing in my POST function? function doAction(prefix) { if ($('#' + prefix + '_actio ...

Animating Text Changes with JavaScript and jQuery

In my HTML, I have an input type="text" element and I want to attach an event handler that triggers when the text is changed. The issue arises because this input's value is dynamically updated by another JavaScript function, causing the event handler ...

When attempting to insert data into a MySQL database using C# Webforms, an ArgumentException is thrown

I am currently in the process of developing a Registration Page using Webforms, with the intention of connecting it to a MySQL database to insert data. However, I keep encountering an ArgumentException error (even though I believe I am following my tutoria ...

Experiencing Issues with MySQL Data Length?

I am currently working with the mysql2 library in conjunction with NodeJS. I have identical code and database structures on both my local machine and a server. Interestingly, when I attempt to upload an image into the "photos" table on my local setup, ever ...

The function Rx.Observable.from does not exist

Recently, I delved into the world of reactive programming in JavaScript using RxJS and decided to try my hand at node.js for the first time. However, I seem to be facing some issues with my code. See below: const array = [ '1', 'Max&apos ...