0

I come from PHP and do not understand how a series of MySQL queries can be written in async NodeJS. For example, take this example from PHP coding:

$mysqli->query("INSERT INTO articles (title) VALUES ('title')");
$article_id = $mysqli->insert_id;

foreach ($tags as $tag) {
    $result = mysqli->query("SELECT tag_id from tags WHERE tag='$tag'");
    if($result->num_rows==1){
        $row=$result->fetch_assoc();
        $tag_id=$row['tag_id'];
    } else {
        $mysqli->query("INSERT INTO tags (tag) VALUES ('$tag')");
        $tag_id=$mysqli->insert_id;
    }

    $mysqli->query("INSERT INTO tag_map (article_id, tag_id) VALUES ($article_id, $tag_id)");
}

How can we write this code in Node.JS?

I specifically mean, the if statement and getting insert_id for the next queries.

1 Answer 1

1

You can get insert id of latest record by this

 let query = "insert into `articles` (title) VALUES ('" + title + "')";

   db.query(query,(err,result) => {
      if(err){
           return res.status(500).send(err);
        }
         console.log(result.insertId)
   })
     .then((articleid)=>{
        tags.forEach((tag)=>{
         let tagQuery = "SELECT tag_id from tags WHERE tag='"+tag+"';
           // get tag_id from tags 
          db.query(query,(err,result) => {
          // if result length is greater tha 0
          if(result.length > 0){
             tag_id = result.tag_id // set tag id
           }
           else{
                // insert tag into db
                let insertTagQuery = "INSERT INTO tags (tag) VALUES ('"+tag+"')';
                db.query(insertTagQuery,(err,result) => {
                if(err){
                  return res.status(500).send(err);
                  }
                let mapTagQuery = 'INSERT INTO tag_map (article_id, tag_id) VALUES ('"+article_id+"', '"+result.tag_id+"')';

                db.query(mapTagQuery,(err,result) => {
                if(err){
                   return res.status(500).send(err);
                  }
                  console.log(result)
               });

             }

           console.log(result.insertId)
        })

       })
     }) ;  
Sign up to request clarification or add additional context in comments.

4 Comments

node-mysql was in my question tags. I know the module, I asked how to get multiple insert_id for the next query.
you can just simply result.insertId after insertion of every record it will return you the insert record id
I know, result.insertId return it. My question is how to continue the queries to insert tags and get their insert_id to use both article_id and tag_id to INSERT into tag_map table.
My problem is the loop after let article_id = result.insertId.

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.