CRUD Nodejs with MySQL

Tram Ho


Hello everyone, continue with the basic Nodejs series, today I will continue to add functions to view details and edit and delete products. Well, forget that in the previous post, after connecting to mysql, we haven’t changed the search function yet, so in this article I will fix the search function as well. Let’s get started now


Edit search function

Simply edit the function

to be like this is okay

In the previous post, we filter by id to get the elements that satisfy the conditions in the array, but now we simply get the product list and where by id sent from the client.


First of all we need to revise the index.pug page a little bit so that we can perform detail view, edit, delete. I have the index.pug page as follows:

Looks like this from the outside

The idea is that when I click on the Detail , I will switch to the detail page, so I need a page that is detail.pug as follows:

And the function in index.js to switch from index page to detail page is as follows:

OK so we have finished the function to view details


The delete function will be simpler than you just need to call the delete function to pass the id and redirect back to the home page. The delete function is as follows:

Here is the result


The update function, I will do the following: First, it will create a page to display data that the user wants to edit. On that page, after the user completes the editing, press the update button, I will call the update function to update the product and return the product list page.

The first will be the function to call the product update page

This function is similar to the function that calls to the product details page, here I call the update page. I have the page update.pug as follows:

Here I show the product that the user wants to fix and because the id attribute I set to be the primary key and automatically incremented so I will leave the input tag of the id attribute readonly to prevent the user from editing the id. After the user has finished editing the title and presses Update , it will call the update function to update data. The update function is as follows:

In this function, I get the data from the update.pug page and send it up and update it to keep the data and finally return the page displaying the product list.

Here is the result:


So I have completed the search function, view details and update and delete the product. In the next article, I will talk about the validation. Again thank you !!!

Share the news now

Source : Viblo