Skip to content

Instantly share code, notes, and snippets.

@brien-crean
Last active March 20, 2019 23:52
Show Gist options
  • Save brien-crean/f64415fe5d7a31f239d9112a04634af9 to your computer and use it in GitHub Desktop.
Save brien-crean/f64415fe5d7a31f239d9112a04634af9 to your computer and use it in GitHub Desktop.
Simple add customer and customer address record

Simple POST endpoint to create a customer record and also a customer address record with associated foreign key

// create: customer and associated address record
app.post("/", (req, res) => {
  // Customer rec
  let insertCustomer = "INSERT INTO Customers (Name) VALUES(?)";
  const customerValues = [req.body.name];
  insertCustomer = mysql.format(insertCustomer, customerValues);

  connection.query(insertCustomer, function(err, result, fields) {
    if (err) throw err;
    // get ID of customer record
    const customerID = result.insertId;

    // Customer_Address rec
    let insertCustomerAddress =
      "INSERT INTO Customer_Addresses (Customer_ID, Street_Address, Postal_Code, Country) VALUES(?,?,?,?)";
    const customerAddress = [
      customerID,
      req.body.street_address,
      req.body.postal_code,
      req.body.country
    ];
    insertCustomerAddress = mysql.format(
      insertCustomerAddress,
      customerAddress
    );

    connection.query(insertCustomerAddress, function(err, result, fields) {
      if (err) throw err;
      let customerID = result.insertId;

    });

    res.send("User Created successfully");
  });
});

Customers Table

ID Name
1 Ryan
2 Jonathan
3 Colin
4 Syed

Customer Addresses Table

ID Customer_ID(FK) Street_Address Postal_Code Country
1 2 123 Big Walk Way 75023 US
2 3 509 Charter Road 90021 US
3 1 999 Night Stalker Road 12345 US
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment