생활코딩/WEBn
[Node.js & MySQL] 테이블 생성
hayjo
2021. 1. 13. 18:57
DB에서 가져온 데이터를 반복문을 이용해 html 테이블(<table><th><td>) 형태로 작성
+기본적인 조작에 필요한 CSS
[강의 출처]opentutorials.org/course/3347/21202
테이블 생성
html에서 테이블을 생성하는 태그는 <table>이다.
그 아래로 제목 <thead>, 행 <tr>, 컬럼(셀 하나하나 자리) <td>가 온다.
<th>는 강조를 위한 제목태그로, 제목 부분에서 <td>를 대신해서 사용하면 된다.
<table>
<thead>
<tr>
<th>#</th>
<th>C1</th>
<th>C2</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Data1</td>
<td>Data2</td>
</tr>
<tr>
<td>2</td>
<td>Data3</td>
<td>Data4</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Foot</td>
<td>.</td>
<td>.</td>
</tr>
</tfoot>
</table>
# | C1 | C2 |
---|---|---|
1 | Data1 | Data2 |
2 | Data3 | Data4 |
결론 | . | . |
기본 값은 테두리 없음이다. 전체 테두리를 쳐보자. html 내에서 css를 실행하려면 <style> 태그를 사용하면 된다.
<style>
table {
border-collapse: collapse;
}
td {
border:1px solid gray;
}
}
</style>
# | C1 | C2 |
---|---|---|
1 | Data1 | Data2 |
2 | Data3 | Data4 |
결론 | . | . |
헤딩 부분은 td가 아니라 th여서 빠졌다. 마저 채우고, 배경색을 넣고, 폰트를 바꿔본다.
<style>
table {
border-collapse: collapse;
}
td, th {
border:1px solid gray;
font-family: fantasy;
}
th {
background-color: #8097e2;
}
}
</style>
표 디자인이 완성되었다.
# | C1 | C2 |
---|---|---|
1 | Data1 | Data2 |
2 | Data3 | Data4 |
Foot | . | . |
콤보박스와 마찬가지로 데이터 입력 작업이 반복되기 때문에, 이 부분을 for문 등으로 처리한다.
var mysql = require('mysql');
var db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'database'
});
db.connect();
// DB 불러오는 부분
db.query('SELECT * FROM dbname', function(err, result){
var tableTag = '<table>\n';
while(i<result.length){
tag += `<tr>
<td>${result[i].name}</td>
<td>${result.[i].profile}</td>
</tr>`;
i++;
}
tag += '</table>';
// 이제 tableTag를 html 페이지로 넘겨서 작성하면 완료;
});
혹시 테이블 안에 버튼을 넣고 싶다면, 똑같이 <td> 안에 <button> 태그를 넣어주면 된다.