Search code examples
mysqlnode.jsexpressxampp

Error in delete DB record using Node.JS and MYSQL


I'm performing CRUD operations using MYSQL and NodeJS express. Their error in deleting a record from DB, I don't know why I was getting a problem as i have copied the delete query from SQL where it is working properly. Here it is 'DELETE FROM tblltest WHERE id=?'. I manually add 'id' like 'DELETE FROM tblltest WHERE id=2' then it will delete the record from DB. Please help me out to solve this issue. Here are my lines of code.

 var express = require('express');
    var mysql = require('mysql');
    var app = express();

var connection = mysql.createConnection({
    
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'sampledb'
    
});

app.delete('/:id' , function(req , resp) {
    connection.query('DELETE FROM `tblltest` WHERE `id`=?' , function(error , rows , fields){
        if(!error){
            
            console.log('Successful deleted!! \n');
            resp.json(rows);
            
        }else{
            console.log('Error in deleting');
        }
        
    });
})

app.listen(1337);

Solution

  • You need to access the id route parameter in your delete API Node method, and then also bind this id value to the delete query:

    app.delete('/:id', function(req, resp) {
        var id = req.params.id;
    
        connection.query('DELETE FROM tblltest WHERE id = ?', [id],
            function(error, rows, fields) {
                if (!error) {
                    console.log('Successful deleted!! \n');
                    resp.json(rows);    
                }
                else {
                    console.log('Error in deleting');
                }
            });
    })