2

I am using normal http request for deleting value from mysql database using node.js. But right now, only values are deleted statically not dynamically. I want to delete the data dynamically by providing the id.

const server = http.createServer();
const reqUrl = url.parse(req.url, true);

server.on('request', (req, res) => {
  if (reqUrl.pathname === '/delete'){

   req.on('end', () => {                        
       let sql = "Delete from students where id=12";     
        connection.query(sql, function (err, result) {
         if (err) throw err;
        console.log(result);
        });
        })
    res.end();   
   }
});

now, after running this code localhost:3000/delete only the id=12 is deleted all time. But I want to do this localhost:3000/delete?id=12 giving input values as id.

I tried to give sql command as "Delete from students where id=?" , but it gave errors. How can I solve this?

1 Answer 1

2

That should be simple.

You just need to receive the param from your request and append it to string.

Here's your updated code.

server.on('request', (req, res) => {
  if (reqUrl.pathname === '/delete'){

   req.on('end', () => {    
       let studid = req.query.id; //Get the student id                    
       let sql = "Delete from students where id="+studid; //append it to query     
        connection.query(sql, function (err, result) {
         if (err) throw err;
        console.log(result);
        });
        })
    res.end();   
   }
});
Sign up to request clarification or add additional context in comments.

4 Comments

but how can I access the id, as it's auto incremented. By giving this, i got reference error, as id is not defined.
Are you passing id as query param. Can you please log req.query and let me know what you are getting? Also, you should be passing id from request url.
TypeError: Cannot read property 'id' of undefined. Values are going to db through parse(body) using 'querystring'
Can you please confirm what is the url you are actually constructing to hit this method? Also please log req.query and see what you are getting..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.