0

This is my use case.

  1. First I insert data to the customer table.
  2. Then I get the insertId for the customer.
  3. Then I try to insert data into address table using that id.

async function createCustomer(req, res, next) {
    const customer = {
        type: req.body.type,
        first_name: req.body.first_name,
        last_name: req.body.last_name,
        email: req.body.email
    };
    
    const first_line = req.body.first_line

    console.log("Customer from front-end", customer);

    try {
        let query1 = "INSERT INTO customer_supplier SET ?";
        connection.query(query1, customer, (error, results) => {
            if (error) {
                console.log("Error", error);
            } else {
                let userId = results.insertId;
                let query2 = "INSERT INTO address (id,first_line) VALUES ?";


                connection.query(query2, [userId, first_line], (error, results) => {
                    if (error) {
                        console.log("error in address ==================================", error)

                    } else {
                        res.json({
                            results: results
                        })
                    }
                })
            }
        });

      
    } catch (error) {
        console.log("error from", error);
        res.json({
            error: error
        });
    }
}

But when I try to insert data into the address table,

code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlMessage: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'36\' at line 1',
  sqlState: '42000',
  index: 0,
  sql: 'INSERT INTO address (id,first_line) VALUES 36' }

Before put this question on stackoverflow I tried so many variations in my insert statement and nothing works for me. How do I achieve this?

1
  • check the data type if id field in address table. I think it is integer in address table and you are getting string from results. Commented Jul 9, 2018 at 10:57

2 Answers 2

1

Your sql is not written correct,you need to add () to wrap the value

let query2 = "INSERT INTO address (id,first_line) VALUES (?,?)";

Below is the grammar to use INSERT INTO

> INSERT INTO table_name (column1, column2, column3, ...) 
> VALUES (value1, value2, value3, ...);
Sign up to request clarification or add additional context in comments.

Comments

0

would you try this one

   let query2 = "INSERT INTO address (id,first_line) VALUES ('userId', 'first_line')"

connection.query(query2, (error, results)

Comments

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.