create account

NodeJS Tutorials #3 - MySQL part 2 by lonelywolf

View this thread on: hive.blogpeakd.comecency.com
· @lonelywolf · (edited)
$87.16
NodeJS Tutorials #3 - MySQL part 2
![](https://images.techhive.com/images/article/2014/09/nodejs-1280x1024-100453402-primary.idge.jpg)

#### What Will I Learn?
Write here briefly the details of what the user is going to learn in a bullet list.

- Insert, export, update and delete data with MySQL with NodeJS

#### Requirements

- MySQL server
- XAMPP
- NodeJS

#### Difficulty

- Basic

#### Tutorial Contents
In this tutorial, you will learn how to insert, export, delete and update data in the database.

#### Curriculum

- [NodeJS Tutorials #1](https://utopian.io/utopian-io/@lonelywolf/nodejs-tutorials-1-creating-a-static-site-node-js)
- [NodeJS Tutorials #2 - Setup MySQL](https://utopian.io/utopian-io/@lonelywolf/nodejs-tutorials-3-mysql-part-1)

#### The Tutorial

### Inserting data

the very basic stuff in mysql is to insert data into our database.

you can be done it on the `phpmyadmin` page if you don't need something dynamically to put into the database and you can use it in your script.

first, do it on phpmyadmin and get the basic syntax of mysql.

go to your database ->

![image.png](https://cdn.utopian.io/posts/cc8dae9ecceae10496f0653641acc7954dacimage.png)

this is my database.

now to be able to contact the database, create a table.

![image.png](https://cdn.utopian.io/posts/124da850ae0074c059de51ddc1979327f800image.png)

the table is the way to contact with the database, you will need multiple tables for big projects, for example, I want to make user system I will need only `users` table but for a forum system I will need for example `users`, `categories` etc.

press `GO` to create the table.

![image.png](https://cdn.utopian.io/posts/632605c2d4eda592ddde20af43a52c089a7bimage.png)

now you need to make the variables for your table (you can add more after you done), most of the time you will want `ID` at any of your tables, to do it you need `A_I` checked and set it to `Primary`.

and then your other variables, for example, I made `text` which is VARCHAR (can store string) with 120 maximum lengths.

Press `save` and you're done with the table.

if all done correctly, you will see something like that >

![image.png](https://cdn.utopian.io/posts/08f3aaaaec631e45a010dbd8815e4c5c0020image.png)

now to use SQL you can go to `SQL` tab >

![image.png](https://cdn.utopian.io/posts/2531f73614f5a82544dc9b1069eb7b0d9945image.png)

![image.png](https://cdn.utopian.io/posts/274af1b106fb69b2bd9d628a3580da455d3aimage.png)

Press the `Insert` button and you will get simple Insert syntax because we set `ID` to `A_I` you don't need to insert it so delete it and `[value_1]`

`note`: you need to use `'` to input strings!

now you have `text` and `[value_2]`, change `[value_2]` to `simple text` and press `GO`

if all have done correctly, you will get this result >

![image.png](https://cdn.utopian.io/posts/67be2f88e04c9562f4736cf5dabc03ce4d6fimage.png)

and now we can see that in the `Browse` tab >

![image.png](https://cdn.utopian.io/posts/758dcbab6515d96663d690038af1f5b559a7image.png)

### Insert, Delete, Export and Update through a NodeJS script
First, you need a basic NodeJS server and setup MySQL on your server,

tutorials at the top of the post!

simple server code >

```
var app = require('http').createServer(handler);
var fs = require('fs');
const mysql = require('mysql')

app.listen(80);

const config = {
  "host": "localhost",
  "user": "root",
  "password": "",
  "base": "mysql_example"
};

var db = mysql.createConnection({
  host: config.host,
  user: config.user,
  password: config.password,
  database: config.base
});

db.connect(function (error) {
  if (!!error)
  throw error;

  console.log('mysql connected to ' + config.host + ", user " + config.user + ", database " + config.base);
});

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
  if (err) {
  res.writeHead(500);
  return res.end('Error loading index.html');
  }

  res.writeHead(200);
  res.end(data);
  });
}
```

so let's make a function for each action.

```
function InsertData(type, string){
  db.query("INSERT INTO `test_table`(`"+type+"`) VALUES(?)", [string], function(err, result){
  console.log(err, result);
  });
}
```

because it's basically you can do it as a function so it will be easy to use, but for advanced I suggest you to just use the normal query function.

so, we made a function called `InsertData`, with 2 variables, `type` - the type of text we want to insert the string to.

`string` - the string/text we need to put on the table.

then we use the function `db.query` this is the function you need to always use to contact the database.

now we use the INSERT function in MySQL and we use the table `test_table` and we use `type(will be text)` to fill with our string.

and in `VALUES` we put `?`, what is it?

the `?` means that the variable will input to the function after its runs, which gives us better secure when we using password etc.

`[string]`, here you put the variables to fill the `?`, for this example, we use `string`.

then we make a function with the error output and the result,
and send it to the console.

![image.png](https://cdn.utopian.io/posts/3152054e636695247320ad7fc130a36052d6image.png)

if all have done correctly this will be your result.

```
mysql connected to localhost, user root, database mysql_example
null OkPacket {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 2,
  serverStatus: 2,
  warningCount: 0,
  message: '',
  protocol41: true,
  changedRows: 0 }
```

the other ones it's basically the same, just some minor changes on the syntax so let's make the other ones.

all of the functions >

```
function InsertData(type, string){
  console.log(type);
  db.query("INSERT INTO `test_table`(`"+type+"`) VALUES(?)", [string], function(err, result){
  console.log(err, result);
  });
}
function ExportData(type, string){
  db.query("SELECT * FROM `test_table` WHERE `"+type+"`=?", [string], function(err, result){
  console.log(err, result);
  });
}
function UpdateData(type, string, newString){
  db.query("UPDATE `test_table` SET `"+type+"`=? WHERE `"+type+"`=?", [newString, string], function(err, result){
  console.log(err, result);
  });
}
function DeleteData(type, string){
  db.query("DELETE FROM `test_table` WHERE `"+type+"`=?", [string], function(err, result){
  console.log(err, result);
  });
}
```

usage of the functions.

Exporting data >

```
ExportData("text", "this is a simple text");
```

results

![image.png](https://cdn.utopian.io/posts/4eb7e0a35d2c213ce22b82d700cc74d7de7dimage.png)

```
null [ RowDataPacket { id: 1, text: 'this is a simple text' },
  RowDataPacket { id: 2, text: 'this is a simple text' },
  RowDataPacket { id: 3, text: 'this is a simple text' } ]
```

Update data >

```
UpdateData("text", "this is a simple text", "this is a text");
```

results >

![image.png](https://cdn.utopian.io/posts/980bfbaada63fdf6a894e621516bb5ae683eimage.png)

```
null OkPacket {
  fieldCount: 0,
  affectedRows: 3,
  insertId: 0,
  serverStatus: 34,
  warningCount: 0,
  message: '(Rows matched: 3 Changed: 3 Warnings: 0',
  protocol41: true,
  changedRows: 3 }
```

Delete data >

```
DeleteData("id", 1);
```

(here I use id instead of text, it's easier to find data with ID)

results >

![image.png](https://cdn.utopian.io/posts/0fd21edc34d0a9686f7cfd641e8bfbbc67c1image.png)


```
null OkPacket {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  serverStatus: 2,
  warningCount: 0,
  message: '',
  protocol41: true,
  changedRows: 0 }
```

and here we're done!

#### Next Tutorial
the next tutorial will be `how to make login page with mysql and nodejs`.

in the tutorial, we will use mysql nodejs and socket.io!

if you find this tutorial useful you can score this post with the new utopian system!

Have a great day!

<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@lonelywolf/nodejs-tutorials-3-mysql-part-2">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 125 others
properties (23)
authorlonelywolf
permlinknodejs-tutorials-3-mysql-part-2
categoryutopian-io
json_metadata"{"community":"utopian","app":"utopian/1.0.0","format":"markdown","repository":{"id":27193779,"name":"node","full_name":"nodejs/node","html_url":"https://github.com/nodejs/node","fork":false,"owner":{"login":"nodejs"}},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","tutorial","nodejs","mysql","steemit"],"links":["https://utopian.io/utopian-io/@lonelywolf/nodejs-tutorials-1-creating-a-static-site-node-js","https://utopian.io/utopian-io/@lonelywolf/nodejs-tutorials-3-mysql-part-1","https://utopian.io/utopian-io/@lonelywolf/nodejs-tutorials-3-mysql-part-2"],"image":["https://images.techhive.com/images/article/2014/09/nodejs-1280x1024-100453402-primary.idge.jpg","https://cdn.utopian.io/posts/cc8dae9ecceae10496f0653641acc7954dacimage.png","https://cdn.utopian.io/posts/124da850ae0074c059de51ddc1979327f800image.png","https://cdn.utopian.io/posts/632605c2d4eda592ddde20af43a52c089a7bimage.png","https://cdn.utopian.io/posts/08f3aaaaec631e45a010dbd8815e4c5c0020image.png","https://cdn.utopian.io/posts/2531f73614f5a82544dc9b1069eb7b0d9945image.png","https://cdn.utopian.io/posts/274af1b106fb69b2bd9d628a3580da455d3aimage.png","https://cdn.utopian.io/posts/67be2f88e04c9562f4736cf5dabc03ce4d6fimage.png","https://cdn.utopian.io/posts/758dcbab6515d96663d690038af1f5b559a7image.png","https://cdn.utopian.io/posts/3152054e636695247320ad7fc130a36052d6image.png","https://cdn.utopian.io/posts/4eb7e0a35d2c213ce22b82d700cc74d7de7dimage.png","https://cdn.utopian.io/posts/980bfbaada63fdf6a894e621516bb5ae683eimage.png","https://cdn.utopian.io/posts/0fd21edc34d0a9686f7cfd641e8bfbbc67c1image.png"],"moderator":{"account":"portugalcoin","time":"2018-04-13T23:14:51.561Z","pending":false,"reviewed":true,"flagged":false},"questions":null,"score":null,"total_influence":null,"staff_pick":null,"config":{"questions":[{"question":"Does the tutorial address a minimum of 3 substantial concepts and no more than 5?","question_id":"tut-1","answers":[{"answer":"3-5 substantial concepts covered in the tutorial.","answer_id":1,"value":10},{"answer":"Less than 3 or more than 5 substantial concepts covered in the tutorial.","answer_id":2,"value":5},{"answer":"No substantial or recognisable concepts.","answer_id":3,"value":0}]},{"question":"Concepts covered in the tutorial are indicated in the post text with a short description of each concept and when appropriate, images?","question_id":"tut-2","answers":[{"answer":"Thorough text and images for concepts covered.","answer_id":1,"value":10},{"answer":"Minimal text and images.","answer_id":2,"value":5},{"answer":"No or very little text and images.","answer_id":3,"value":0}]},{"question":"Does the contributor provide supplementary resources, such as code and sample files in the contribution post or a GitHub repository?","question_id":"tut-3","answers":[{"answer":"Yes","answer_id":1,"value":10},{"answer":"No","answer_id":2,"value":0}]},{"question":"Is the tutorial part of a series?","question_id":"tut-4","answers":[{"answer":"Yes.","answer_id":1,"value":10},{"answer":"Yes, but first entry in the series.","answer_id":2,"value":5},{"answer":"No.","answer_id":3,"value":0}]},{"question":"Is there an outline for the tutorial content at the beginning of the post?","question_id":"tut-5","answers":[{"answer":"Yes.","answer_id":1,"value":10},{"answer":"Yes, but not detailed enough or does not cover all sections.","answer_id":2,"value":5},{"answer":"No.","answer_id":3,"value":0}]},{"question":"Does the writing style meet the Utopian standard considering formalness, informativeness and clarity of the content?","question_id":"c-1","answers":[{"answer":"It is formal, informative and well written with clear content.","answer_id":1,"value":10},{"answer":"It is informative with clear content but not formal enough.","answer_id":2,"value":5},{"answer":"The contribution could be more informative or contains unrelated information, formality and clarity of the content are good enough.","answer_id":3,"value":4},{"answer":"Not all sections were clear enough but overall holds value for the project.","answer_id":4,"value":2},{"answer":"Not at all.","answer_id":5,"value":0}]},{"question":"Was the provided category template for the editor followed?","question_id":"c-2","answers":[{"answer":"All points of the template were included with additional points as well.","answer_id":1,"value":5},{"answer":"The template was followed without additions.","answer_id":2,"value":4},{"answer":"The template was edited but the points were covered in different way.","answer_id":3,"value":3},{"answer":"Not all points of the template were covered in the contribution but the structure is clear enough.","answer_id":4,"value":3},{"answer":"The template was not followed but the structure is clear enough.","answer_id":5,"value":2},{"answer":"The contents are not clearly structured at all.","answer_id":6,"value":0}]},{"question":"Did the contributor tag other users?","question_id":"c-3","answers":[{"answer":"No other users were tagged by the contributor.","answer_id":1,"value":5},{"answer":"Used tags are reasonable and all tagged people are connected to the project and/or the contribution.","answer_id":2,"value":5},{"answer":"The contribution contains mentions of other users that are not directly related to the contribution but related in other ways.","answer_id":3,"value":2},{"answer":"The contributor misuses tagging of other users.","answer_id":4,"value":0}]},{"question":"Did the contributor ask for upvotes, resteems, follows or witness vote?","question_id":"c-4","answers":[{"answer":"No","answer_id":1,"value":5},{"answer":"Yes, but not in a way that disturbs readability. ","answer_id":2,"value":5},{"answer":"Yes.","answer_id":3,"value":0}]},{"question":"Was a graphical content like images, charts, videos or screenshots included?","question_id":"c-5","answers":[{"answer":"Yes, the graphical content is included and adds more value to the contribution.","answer_id":1,"value":5},{"answer":"No but the contribution works well without graphical content well.","answer_id":2,"value":4},{"answer":"Yes, but most of the graphical content’s purpose is just for presentational matters.","answer_id":3,"value":3},{"answer":"No relevant or useful graphical content is included in the contribution.","answer_id":4,"value":0}]},{"question":"How would you rate the overall added value?","question_id":"c-6","answers":[{"answer":"Extraordinary value to both the project and the open source community overall.","answer_id":1,"value":20},{"answer":"Significant value to the project or open source community.","answer_id":2,"value":15},{"answer":"Some value to the project or open source community.","answer_id":3,"value":10},{"answer":"Little value to the project or open source community.","answer_id":4,"value":5},{"answer":"No obvious value to project or open source community.","answer_id":5,"value":0}]}]}}"
created2018-04-12 10:44:15
last_update2018-04-13 23:14:51
depth0
children3
last_payout2018-04-19 10:44:15
cashout_time1969-12-31 23:59:59
total_payout_value63.506 HBD
curator_payout_value23.658 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length7,941
author_reputation25,295,791,457,391
root_title"NodeJS Tutorials #3 - MySQL part 2"
beneficiaries
0.
accountutopian.pay
weight1,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id49,652,893
net_rshares21,390,098,514,649
author_curate_reward""
vote details (189)
@portugalcoin ·
$0.77
Thank you for the contribution It has been approved.

----------------------------------------------------------------------
Need help? Write a ticket on https://support.utopian.io.
Chat with us on [Discord](https://discord.gg/uTyJkNm).

**[[utopian-moderator]](https://utopian.io/moderators)**
👍  
properties (23)
authorportugalcoin
permlinkre-lonelywolf-nodejs-tutorials-3-mysql-part-2-20180413t231724714z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-04-13 23:17:30
last_update2018-04-13 23:17:30
depth1
children1
last_payout2018-04-20 23:17:30
cashout_time1969-12-31 23:59:59
total_payout_value0.767 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length294
author_reputation598,828,312,571,988
root_title"NodeJS Tutorials #3 - MySQL part 2"
beneficiaries
0.
accountutopian.pay
weight1,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id49,929,586
net_rshares244,929,536,507
author_curate_reward""
vote details (1)
@lonelywolf ·
Thanks!
properties (22)
authorlonelywolf
permlinkre-portugalcoin-re-lonelywolf-nodejs-tutorials-3-mysql-part-2-20180414t102730429z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"app":"steemit/0.1"}
created2018-04-14 10:27:39
last_update2018-04-14 10:27:39
depth2
children0
last_payout2018-04-21 10:27:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length7
author_reputation25,295,791,457,391
root_title"NodeJS Tutorials #3 - MySQL part 2"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id50,003,179
net_rshares0
@utopian-io ·
### Hey @lonelywolf I am @utopian-io. I have just upvoted you!
#### Achievements
- People loved what you did here. GREAT JOB!
- You have less than 500 followers. Just gave you a gift to help you succeed!
- Seems like you contribute quite often. AMAZING!
#### Utopian Witness!
<a href="https://discord.gg/zTrEMqB">Participate on Discord</a>. Lets GROW TOGETHER!
- <a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for my Witness</a>
- <a href="https://v2.steemconnect.com/sign/account-witness-proxy?proxy=utopian-io&approve=1">Proxy vote to Utopian Witness</a>

**Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x**
properties (22)
authorutopian-io
permlinkre-lonelywolf-nodejs-tutorials-3-mysql-part-2-20180414t120455344z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-04-14 12:04:54
last_update2018-04-14 12:04:54
depth1
children0
last_payout2018-04-21 12:04:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length760
author_reputation152,955,367,999,756
root_title"NodeJS Tutorials #3 - MySQL part 2"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id50,016,003
net_rshares0