Ben Shan
Ben Shan

Reputation: 9

Node.js mySQL syntax error when posting data

I'm new to Node.js and servers in general and have just started trying to implement a database into my server. I have the mySQL database and table set up with the server connecting to the database and the server beginning to process the SQL query, however it breaks the query due to a syntax error within my INSERT, I've been looking at the forums and have changed my code a couple of times with no luck... Please help if you can see where I've gone wrong, Thank you!

router.post('/', (req, res, next) => {
    console.log(req.name);
    const imageJSON = {
        //attributes of item that server will request (more important for db
        name: req.body.name,
        image: req.body.image
    };
    //console.log(req.body.image);

    res.status(201).json({
        message: imageJSON
    });
    connection.connect(function(err){
        if(!err) {
            console.log("Database is connected ... nn");
        } else {
            console.log("Error connecting database ... nn");
        }
    });
    var post = {id: 1, name: req.body.name, image: req.body.image};
    connection.query('INSERT INTO "images" ("id", "name", "image") VALUES ?', post,
        function(err, rows, fields) {
            connection.end();
            if (!err)
                console.log('The solution is: ', rows);
            else
                console.log('Error while performing Query.', err);
        });
    //connection.end();
});

Upvotes: 1

Views: 413

Answers (1)

kimobrian254
kimobrian254

Reputation: 577

Try this:

var post = {id: 1, name: req.body.name, image: req.body.image};
var query = connection.query('INSERT INTO images SET ?', post, function 
   (error, rows, fields) {
      // ... operation on result
});

Upvotes: 1

Related Questions