Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
41 views13 pages

Famous Quotes - CRUD Operations (Signed)

Uploaded by

hemija4875
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views13 pages

Famous Quotes - CRUD Operations (Signed)

Uploaded by

hemija4875
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

California State University Monterey Bay

School of Computing and Design


CST 336 Internet Programming

Famous Quotes - CRUD Operations


In this lab, we’ll create an app allowing users to create new records in the “authors” and
“quotes” tables. Users can also update existing records and delete records from the
tables.

In this lab, we’ll practice the following topics:

● Connecting to a MySQL database from an Express app


● Creating and running POST routes
● Adding new records into a MySQL database table
● Updating existing records
● Deleting database records

For this lab, we’ll continue using the q_quotes and q_authors tables that we created in the
previous lab.

Here are a few screenshots of the app we’ll build, however, the tutorial only addresses the
functionality. You’ll need to add the CSS styles.

Home Page
It will include four
buttons:

● Add Authors
● Add Quotes
● List Authors
● List Quotes

1
California State University Monterey Bay
School of Computing and Design
CST 336 Internet Programming

Add Author/Quote
When clicking on the “Add Author” or “Add Quote” buttons, users will be taken to the
corresponding view. Each view will include a form to get all values for new authors and new
quotes.

List Authors/Quotes
These views will list the authors and quotes in the database along with links to update or delete
each record.

2
California State University Monterey Bay
School of Computing and Design
CST 336 Internet Programming

1.Set up the App and Create the Folder Structure


1) Create a new folder within your “labs” folder. You can call it “lab6”, “quoteAdmin”
or any other name of your choice.

2) Open a terminal window. Go inside the new folder you just created and run the
following command to generate the package.json file.
npm init -y

3) Install the packages that the app will use by running the command:
npm install express ejs mysql2

4) Create the folder structure of a default Express app.


Within the app folder create two more folders:
public and views
Within the views folder create a partials folder
Within the public folder create three folders:
css, img and js

5) Create the index.mjs file and initialize it with the basic code of an Express app
that uses MySQL. Copy the code from the “Express - MySQL Code Snippet”
page located in Canvas.

6) In the index.mjs file, locate the code that


creates the database connection pool.
Replace the values in red (hostname,
username, password, and database). If you’re
using FastComet, refer to the Create a
Database in FastComet tutorial for these values.

7) Test the database connection.


Start the application by executing the
command: node index.mjs
In the browser, go to the following URL to test the db connection.
https://localhost:3000/dbTest

3
California State University Monterey Bay
School of Computing and Design
CST 336 Internet Programming

2.Create the Home Page


1) Create an index.ejs file within the views folder.

2) In the index.ejs file, add the following code to display


four buttons.
Observe that each of them has its corresponding route.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CRUD Operations</title>
</head>
<body>

<h1> Famous Quotes - Admin Section </h1>

<form action="/author/new">
<button>Add Authors</button>
</form><br>

<form action="/quote/new">
<button>Add Quotes</button>
</form><br>

<form action="/authors">
<button>List Authors</button>
</form><br>

<form action="/quotes">
<button>List Quotes</button>
</form>

</body>
</html>

4
California State University Monterey Bay
School of Computing and Design
CST 336 Internet Programming

3) Modify the index.mjs file to render the index.ejs view in the root route

4) Run the app, you should see the landing page which
includes just the buttons. You can add CSS to it later.

3.Create the Route and View to Add Authors


1) Modify the index.mjs file to add the /author/new route

2) Create a new “newAuthor.ejs” file within the views folder. This view will
include an HTML form to get all the data to add new authors.
Copy and paste the code below within the newAuthor.ejs file.

<h1>Adding a new Author</h1>

<form method="POST" action="/author/new">


First Name:
<input type="text" name="fName"><br>
Last Name:
<input type="text" name="lName"><br>
Date of Birth:
<input type="date" name="birthDate">
<br>
<button>Add Author</button>
</form>

5
California State University Monterey Bay
School of Computing and Design
CST 336 Internet Programming

Observe that the form is using the POST method. The POST method is used
when submitting data that needs to be stored in the database.

For now, the form includes three fields, you’ll need to add all remaining ones.

3) Modify the index.mjs file to add the “/author/new” route.

app.post("/author/new", async function(req, res){


let fName = req.body.fName;
let lName = req.body.lName;
let birthDate = req.body.birthDate;
let sql = `INSERT INTO q_authors
(firstName, lastName, dob)
VALUES (?, ?, ?)`;
let params = [fName, lName, birthDate];
const [rows] = await conn.query(sql, params);
res.render("newAuthor",
{"message": "Author added!"});
});

The SQL statement uses question marks as placeholders to prevent SQL injection.

Observe that the route must use “app.post” since it’s the route for a form using the
POST method. When using the POST method, the information is sent within the body
of the Request, so we need to use “req.body” to get the values submitted through
the form.

For Express to be able to parse values coming from an HTML Form using the POST
method, we need to include the following line of code in the index.mjs file. This line of
code was already included when copying the code snippet to initialize the Express
app… just make sure that it’s there!
.

6
California State University Monterey Bay
School of Computing and Design
CST 336 Internet Programming

4) Run the app and test it. Fill out the form and submit it. Check the database and
make sure that the new record was added.

The /author/new POST route is sending a “message” parameter with the value
“Author Added!”. Let’s display this message in the newAuthor.ejs file.

Given that the /author/new GET route is not sending this message, we’ll get an
error complaining that “message” is not defined when trying to access the form to
add a new author. To prevent the error, use the following condition which checks
whether the variable “message” is not undefined.

<% if (typeof message != "undefined"){ %>


<h3><%=message%></h3>
<% } %>

5) Add all remaining fields to the form and also to the SQL statement so all values
are added to the database table.

4. Create a Route to Display the List of Authors


In this section, we’ll display the list of all authors with links to update and delete each of
them.

Recall that when we created the Home Page, we


added a button to list all authors (screenshot to
the right). The action of the form is /authors, so
we’ll need to implement this route.

7
California State University Monterey Bay
School of Computing and Design
CST 336 Internet Programming

1) In the index.mjs file, add a new route to render the list of authors. You can add it
right below the last route.

app.get("/authors", async function(req,


res){
let sql = `SELECT *
FROM q_authors
ORDER BY lastName`;
const [rows] = await conn.query(sql);
res.render("authorList", {"authors":rows});
});

2) Within the views folder, create a new authorList.ejs file


Copy and paste the following code within it.
Observe that we’re looping through the array of authors to display their first and
last names. We’re also appending links to edit and delete each record. The links
pass the corresponding authorId as a parameter.

<body>

<h1> Update/Delete Authors </h1>

<% for (i=0; i < authors.length; i++) { %>

<a
href="/author/edit?authorId=<%=authors[i].a
uthorId%>">UPDATE</a>

<a
href="/author/delete?authorId=<%=authors[i]
.authorId%>">DELETE</a>

<%=authors[i].firstName%>
<%=authors[i].lastName%> <br>

<% } %>

8
California State University Monterey Bay
School of Computing and Design
CST 336 Internet Programming

3) Restart the server and click on the “List Authors” button.

4) Check the code generated by the ejs tags.


For testing purposes, it’s helpful to verify that the code generated by the ejs tags
includes the expected information. When seeing the list of authors on the web
page, right-click on the page and select “View Page Source”

You should see something similar to


the screenshot to the right. The
corresponding authorId should be
included on each of the links.

5. Create Routes to Update Author Data


When updating existing data from a database, the forms should be pre-populated
with the current values. In this section, we’ll pre-populate the form and then
implement a route to update the data in the database.

1) Modify the index.mjs file to add the /author/edit route, which receives the
authorId when clicking on any of the author names. This route retrieves all data
for the selected author. Observe that we’re using the MySQL function
“DATE_FORMAT” to get the date in the YYYY-MM-DD format for the date to be
displayed properly in the form. We’re using the alias “dobISO”, which we’ll use to
display the date of birth.

app.get("/author/edit", async function(req,


res){

let authorId = req.query.authorId;

let sql = `SELECT *,


DATE_FORMAT(dob, '%Y-%m-%d') dobISO
FROM q_authors
WHERE authorId = ${authorId}`;
const [rows] = await conn.query(sql);
res.render("editAuthor", {"authorInfo":rows});
});

9
California State University Monterey Bay
School of Computing and Design
CST 336 Internet Programming

2) Create the editAuthor.ejs file within the views folder.


This file will include a similar form as the addAuthor.ejs
file. However, the main difference is that the form
elements should be pre-populated with the values from
the database.

To pre-populate text boxes, we add the “value” attribute, like this:


<input type="text" name="firstName" value="pre-populated value">

To pre-populate radio buttons and checkboxes, we add the “checked” attribute to


display them as checked by default, like this:
<input type="radio" name="sex" value="M" checked>

To pre-populate dropdown menus, we add the “selected” attribute within the


corresponding option, like this:
<option value="M" selected> Male </option>

Copy the code on the following page and paste it into the editAuthor.ejs file.

Observe the following items in the code:

a) The form uses the POST method because the data will be stored in
the database.

b) The authorId is passed as a hidden element. We need the


authorId to be able to update the right record. It won’t be displayed
on the web page but you can see it when using “View Page
Source”.

c) The text boxes use the “value” attribute to pre-populate data.

d) The radio buttons use the “checked” attribute within a condition to


check the appropriate check box (male or female)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CRUD Operations</title>
</head>

10
California State University Monterey Bay
School of Computing and Design
CST 336 Internet Programming
<body>

<h1>Updating Author Data</h1>

<form method="POST" action="/author/edit">


<input type="hidden" name="authorId" value="<%=authorInfo[0].authorId%>">

First Name:
<input type="text" name="fName" value="<%=authorInfo[0].firstName%>">
<br>

Last Name:
<input type="text" name="lName" value="<%=authorInfo[0].lastName%>">
<br>

Date of Birth:
<input type="date" name="dob" value="<%=authorInfo[0].dobISO%>">
<br>

Sex:
<input type="radio" name="sex" value="M"

<% if (authorInfo[0].sex == "M") { %>


checked
<% } %>

> Male

<input type="radio" name="sex" value="F"

<% if (authorInfo[0].sex == "F") { %>


checked
<% } %>

> Female
<br>

<button>Update Author</button>

</form>

</body>
</html>

11
California State University Monterey Bay
School of Computing and Design
CST 336 Internet Programming

3) Test the code you just added. You


should be able to see the
corresponding information for any
author selected.

4) Modify the index.mjs file to implement the /author/edit route using the
POST method. We’re using placeholders in the SQL statement to prevent
SQL injection. Observe that once the record is updated, we’re redirecting
to the /authors route to display the list of authors.

app.post("/author/edit", async function(req, res){


let sql = `UPDATE q_authors
SET firstName = ?,
lastName = ?,
dob = ?,
sex = ?
WHERE authorId = ?`;

let params = [req.body.fName,


req.body.lName, req.body.dob,
req.body.sex,req.body.authorId];
const [rows] = await conn.query(sql,params);
res.redirect("/authors");
});

5) Test your code. Update the first name, last name, sex, and date of birth. The
updated values should be pre-populated when selecting the same author again.

6) Add all the remaining fields to the Update Author form.

12
California State University Monterey Bay
School of Computing and Design
CST 336 Internet Programming

6.Create a Route to Delete Authors


When listing all authors we have already added a link to delete each record. Screenshot
below:

In this section, we’ll implement the route to delete the author being clicked on.
Consider adding a few fake authors so you can test deleting them.

1) Modify the index.mjs file to include the /author/delete route

2) Test the application. You should be able to add, update, and delete authors.

It’s Your Turn!


Implement the following features:

● List all quotes and add links to update and delete each one
● Implement routes to update quotes, display the pre-populated form
● Implement a route to delete quotes

13

You might also like