1

I'm trying to build an app where an user can registry/login and save his favorites movies. Here's the database

enter image description here

This is my first project using MySQL and i found it hard at first to insert/get data for authentification but i managed to do it.

Now i'm trying to have a form where the user can insert movies, but i'm not sure how to do it, since i think i need to have multiple insert queries for : movies directors, user_movies...

What i tried :

app.post("/add", (req, res) => {

const userId = req.body.userId;
const title = req.body.title;
const year = req.body.year;
const image_url = req.body.image_url;
const runtime = req.body.runtime;
const rating = req.body.rating;
const director = req.body.director;
const genre = req.body.genre;
const description = req.body.description;

    db.query('insert into movies (title, year,image_url,runtime, rating, description)values(?, ?,?,?,?,?)',
        [title, year, image_url, runtime, rating, description], (err, result) => {
            console.log(err);
            res.send(result);
        }
    )
    db.query('insert into directors (name) values(?)',
        [director], (err, result) => {
            console.log(err);
            res.send(result);
    });
    db.query('insert into genres (name) values(?)',
        [genre], (err, result) => {
            console.log(err);
            res.send(result);
    });
});

})

klaus_bathory
  • 158
  • 2
  • 13
  • You could use a stored procedure, see [Using Mysql to do multiple INSERT on linked tables](https://stackoverflow.com/questions/10075279/using-mysql-to-do-multiple-insert-on-linked-tables). Advantage is that you will have all SQL-stuff in 1 place. – Luuk Jun 30 '21 at 18:59
  • Thank you, @Luuk! That is what i need! Post it so i can accept it as the solution. – klaus_bathory Jun 30 '21 at 19:11
  • You better give you votes to the person who answered the qeustion I was directing you to..... – Luuk Jun 30 '21 at 19:20

1 Answers1

1

@Luuk provides a good approach to solving this with the use of Stored Procedures. That can be helpful and efficient particularly when you need a newly created value from insert_1 to be used in insert_2 for example.

In your question you appear to already have all of the data your queries require.

If you would like to accomplish this entirely within your Node app and not use a stored procedure, you can do so by enabling the multipleStatements config option.

An example is included below based on your sample code. In the first line of the connection config you will see where the multipleStatements: true is defined.

const mysql = require('mysql');

const connection = mysql.createPool({
  multipleStatements: true, // required for multiple statements
  connectionLimit: 10,
  host: process.env.DB_HOST || '127.0.0.1',
  user: process.env.DB_USER || 'local_user',
  password: process.env.DB_PASSWORD || 'local_password',
  database: process.env.DB_NAME || 'local_database',
  charset: 'utf8mb4' // necessary if you might need support for emoji characters
});

const db = connection;

app.post("/add", (req, res) => {
  let userId = req.body.userId;
  let title = req.body.title;
  let year = req.body.year;
  let image_url = req.body.image_url;
  let runtime = req.body.runtime;
  let rating = req.body.rating;
  let director = req.body.director;
  let genre = req.body.genre;
  let description = req.body.description;

  let query_1 = `INSERT INTO movies (title, year, image_url, runtime, rating, description) VALUES (?, ?, ?, ?, ?, ?); `;
  let query_2 = `INSERT INTO directors (name) VALUES (?); `;
  let query_3 = `INSERT INTO genres (name) VALUES (?);`;

  db.query(
    query_1 + query_2 + query_3, 
    [title, year, image_url, runtime, rating, description, director, genre], 
    (err, results, fields) => {
      if (error) throw error;
      // results is an array with one element for every statement in the query:
      console.log(results[0]); // query_1 results
      console.log(results[1]); // query_2 results
      console.log(results[2]); // query_3 results
      res.send({all_result: results});
    });
  }
);

Be aware that support for multiple statements comes with increased security risks such as SQL injection attacks. Always be diligent to ensure values are properly escaped.

dusthaines
  • 1,320
  • 1
  • 11
  • 17