본 게시글은 유튜브 생활코딩 온라인강의를 시청한 후 학습한 정보를 기록하는 목적의 게시글입니다.
생각의 흐름에 따라 작성된 게시글입니다. 가독성이 떨어질 수 있습니다.
생활코딩
일반인에게 프로그래밍을 알려주는 온라인/오프라인 활동 입니다.
www.youtube.com
생활코딩
hello world 생활코딩의 세계에 오신 것을 환영합니다. 생활코딩은 일반인들에게 프로그래밍을 알려주는 무료 온라인, 오프라인 수업입니다. 어떻게 공부할 것인가를 생각해보기 전에 왜 프로그래밍을 공부하는 이유에 대한 이유를 함께 생각해보면 좋을 것 같습니다. 아래 영상을 한번 보시죠. 온라인 강의 소개 입문자의 가장 큰 고충은 '무엇을 모르는지 모르는 상태'일 겁니다. 온라인에는 프로그래밍을 익히는 데 필요한 거의 모든 정보가 있지만, 이 지식들은
opentutorials.org
생활코딩 WEP3 PHP & MySQL을 수강하기 위한 선수과목인
WEB2 - PHP와 DATABASE2 - MySQL에 대한 수강 기록입니다.
수강 일정은 야학의 수강계획표에 따릅니다.
#0.
대규모의 반복적인 작업을 처리할 수 있는 반복문이 왜 필요한지에 대한 예고편입니다.
반복문이란, 정해진 조건 내에서 코드를 반복하여 실행하고자 할 때 사용되는 문법이다.
#1.
PHP 반복문의 기본적인 형식을 살펴보는 시간입니다.
PHP: while - Manual
while($a++ <= 100000000); : ' ,$x1, 's', PHP_EOL;$t3 = microtime(true);for($a=0;$a <= 1000000000;$a++);$t4 = microtime(true);$x2 = $t4 - $t3;echo PHP_EOL,'> for($a=0;$a <= 100000000;$a++); : ' ,$x2, 's', PHP_EOL;$t5 = microtime(true);$a=0; for(;$a++ <= 100
www.php.net
<?php
/* example 1 */
$i = 1;
while ($i <= 10) {
echo $i++; /* the printed value would be
$i before the increment
(post-increment) */
}
/* example 2 */
$i = 1;
while ($i <= 10):
echo $i;
$i++;
endwhile;
?>
while (expr)
statement
expr, 값 이 참일 동안 statement가 실행되는 반복문으로, php에서 가장 간단한 형태의 반복문이다.
현재는 배우는 단계이므로 expr에 boolean type의 데이터가 들어온다고 생각하자.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Loop</title>
</head>
<body>
<h1>while</h1>
<?php
echo '1<br>';
$i = 0;
while($i < 3){
echo '2<br>';
$i = $i + 1;
}
echo '3<br>';
?>
</body>
</html>
#2.
배열이 무엇인지 살펴보고, 그 형식을 배우는 시간입니다.
배열이란 문법적으로 반복문과는 별개이지만, 반복문과 매우 밀접한 연관관계를 갖고 있다.
배열이란 곧 데이터의 수납상자의 역할을 수행한다.
PHP: array - Manual
The following function (similar to one above) will render an array as a series of HTML select options (i.e. " ... "). The problem with the one before is that there was no way to handle , so this function solves that issue.function arrayToSelect($option, $s
www.php.net
array ( mixed ...$values ) : array
<?php
$fruits = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>
위와 같은 방법들로 php에서 array를 선언할 수 있다.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Array</title>
</head>
<body>
<h1>Array</h1>
<?php
$coworkers = array('egoing', 'leezche', 'duru', 'taeho');
echo $coworkers[1].'<br>';
echo $coworkers[3].'<br>';
var_dump(count($coworkers));
array_push($coworkers, 'graphittie');
var_dump($coworkers);
?>
</body>
</html>
배열을 선언한 변수와 [], index를 활용하여 배열에 담긴 데이터를 꺼낼 수 있다.
PHP: var_dump - Manual
Howdy!I am working on a pretty large project where I needed to dump a human readable form of whatever into the log files... and I thought var_export was too difficult to read. BigueNique at yahoo dot ca has a nice solution, although I needed to NOT modify
www.php.net
var_dump 함수는 표현식에 대한 구조화 된 정보를 표시한다.
(위의 코드에서는 `int(4)`로 표시된다.)
PHP: array_push - Manual
Add elements to an array before or after a specific index or key: $v){ if($k==$pos)$R=array_merge($R,$in); $R[$k]=$v; } }return $R;}function array_push_after($src,$in,$pos){ if(is_int($pos)) $R=array_m
www.php.net
array_push 함수는 array를 스텍으로 취급하여 변수를 array에 push하는 역할을 수행한다.
array_push 에제
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>
array_push 에제 출력값
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)
* Stack이란?
Stack (abstract data type) - Wikipedia
From Wikipedia, the free encyclopedia Jump to navigation Jump to search Abstract data type Similar to a stack of plates, adding or removing is only possible at the top. Simple representation of a stack runtime with push and pop operations. In computer scie
en.wikipedia.org
PHP: Stack - Manual
The Stack class (No version information available, might only be in Git) Introduction A Stack is a “last in, first out” or “LIFO” collection that only allows access to the value at the top of the structure and iterates in that order, destructively.
www.php.net
[JAVA/자료구조] 강의노트 2강 上 : 스텍(Stack) 1차원 배열(Array-Based), 연결 리스트(Linked List), 괄호
강의노트 2강에서는 자료구조 중 Stack과 Queue에 대하여 공부해보고자 합니다. 먼저 Stack에 대하여 알아보겠습니다. 1) 스텍(Stack) 스텍은 자료를 저장하는 방식으로 LIFO 구조를 따릅니다. LIFO는 Last-
xd-jaewon.tistory.com
#3-1.
반복문, 배열, 조건문을 망라해서 웹애플리케이션을 제작해보는 수업입니다.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1><a href="/index.php">WEB</a><h1>
<ol>
<li><a href="index.php?id=HTML">HTML</a></li>
<li><a href="index.php?id=CSS">CSS</a></li>
<li><a href="index.php?id=JavaScript">JavaScript</a></li>
</ol>
<h2>
<?php
$value = isset($_GET['id']) ? $_GET['id'] : '';
echo $value;
?>
</h2>
<?php
if($value){
echo file_get_contents("data/".$value);
}
?>
</body>
</html>
현재 data라는 파일 디렉토리 안에 파일들을 읽어서 자동적으로 링크태크를 추가하는 기능을 구현하고자 한다.
그렇다면 우리는 php문법으로 file list를 directory에서 가져오는 방법을 알아야 한다.
PHP: scandir - Manual
Scandir on steroids: For when you want to filter your file list, or only want to list so many levels of subdirectories...
sandir 예제
<?php
$dir = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);
print_r($files1);
print_r($files2);
?>
sandir 출력값
Array
(
[0] => .
[1] => ..
[2] => bar.php
[3] => foo.txt
[4] => somedir
)
Array
(
[0] => somedir
[1] => foo.txt
[2] => bar.php
[3] => ..
[4] => .
)
이 scandir을 이용해서 우리가 하고자 하는 작업을 구현해보자.
파일의 경로를 지정할때 ` . `은 현재 디렉토리, ` .. `은 부모 디렉토리를 가르키게 된다.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1><a href="/index.php">WEB</a><h1>
<ol>
<?php
$list = scandir('./data');
var_dump($list)
?>
</ol>
<h2>
<?php
$value = isset($_GET['id']) ? $_GET['id'] : '';
echo $value;
?>
</h2>
<?php
if($value){
echo file_get_contents("data/".$value);
}
?>
</body>
</html>
위와 같이 코드를 변경하였을 때 아래와 같은 결과를 소스코드에서 확인할 수 있다.
array(5) {
[0]=>
string(1) "."
[1]=>
string(2) ".."
[2]=>
string(3) "CSS"
[3]=>
string(4) "HTML"
[4]=>
string(10) "JavaScript"
}
#3-2.
이제 배열에 담긴 원소를 더 이상 꺼낼 수 없을 때까지 꺼낼 차례다.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1><a href="/index.php">WEB</a><h1>
<ol>
<?php
$list = scandir('./data');
#var_dump($list)
$i = 0;
while($i < 5){
echo "<li>$list[$i]</li>\n";
$i = ++$i;
}
?>
</ol>
<h2>
<?php
$value = isset($_GET['id']) ? $_GET['id'] : '';
echo $value;
?>
</h2>
<?php
if($value){
echo file_get_contents("data/".$value);
}
?>
</body>
</html>
위의 코드는 어떤가,
얼핏 보면 잘 동작하는 것 처럼 보일 수도 있지만,
만약 data 디렉토리에 새로운 파일이 추가된다면 우리는 while의 조건을 갱신시켜줘야 할 것이다.
그렇다고 처음부터 너무 높은 숫자를 할당해버리면,
프로그렘적으로 깔끔한 코드도 아니거니와, 할당되지 않은 값을 찾을 때 나타나는 에러인
Undefined offset에러를 만날 것이다.
그렇다면 이것을 어떻게 해결할 수 있을까?
#3-3.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1><a href="/index.php">WEB</a><h1>
<ol>
<?php
$list = scandir('./data');
#var_dump($list)
$i = 0;
while($i < count($list)){
echo "<li>$list[$i]</li>\n";
$i = ++$i;
}
?>
</ol>
<h2>
<?php
$value = isset($_GET['id']) ? $_GET['id'] : '';
echo $value;
?>
</h2>
<?php
if($value){
echo file_get_contents("data/".$value);
}
?>
</body>
</html>
count()를 이용하여 배열의 길이를 찾아내어 활용하면 이를 해결할 수 있다.
PHP: count - Manual
In special situations you might only want to count the first level of the array to figure out how many entries you have, when they have N more key-value-pairs. [ 'bla1' => [ 0 => 'asdf', 1 => 'asdf',
www.php.net
아직까지 문제는 있다. 출력되는 결과를 보면 현재 디렉토리를 나타내는 ` . ` 과
부모 디렉토리를 나타내는 ` .. ` 이 출력되는 것을 확인할 수 있다.
이를 이전 시간에 학습한 가정문을 통해 제거해주도록 하자.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1><a href="/index.php">WEB</a><h1>
<ol>
<?php
$list = scandir('./data');
#var_dump($list)
$i = 0;
while($i < count($list)){
if($list[$i] != '.' && $list[$i] != '..'){
echo "<li>$list[$i]</li>\n";
}
$i = ++$i;
}
?>
</ol>
<h2>
<?php
$value = isset($_GET['id']) ? $_GET['id'] : '';
echo $value;
?>
</h2>
<?php
if($value){
echo file_get_contents("data/".$value);
}
?>
</body>
</html>
PHP의 논리연산자를 사용하여 코딩을 강의와 조금 바꿔보았다.
PHP: Logical Operators - Manual
To assign default value in variable assignation, the simpliest solution to me is: It works because, first, $v is assigned the return value from my_function(), then this value is evaluated as a part of a logical operation:* if the left side is false, null,
www.php.net
이제 우리가 원하는 기능을 모두 구현하였으니 아래의 코드처럼 link를 달아 코드를 완성하자.
while($i < count($list)){
if($list[$i] != '.' && $list[$i] != '..'){
echo "<li><a href=\"index.php?id=$list[$i]\">$list[$i]</a></li>\n";
}
$i = ++$i;
}
'오픈튜토리얼스 > 생활코딩 : Web3 - PHP&MySQL' 카테고리의 다른 글
[생활코딩|PHP Day7] PHP의 함수 만들기 예고 / PHP 함수의 형식 / PHP 함수의 활용 (0) | 2020.11.19 |
---|---|
[생활코딩|MySQL Day5] 관계형 데이터베이스의 필요성 / 테이블 분리하기 / 관계형 데이터베이스의 꽃 JOIN (0) | 2020.11.18 |
[생활코딩|PHP Day5] PHP Boolean과 비교연산자 / PHP의 조건문의 형식 / PHP의 조건문 활용 (0) | 2020.11.12 |
[생활코딩|MySQL Day4] MySQL의 CRUD / SQL의 INSERT · SELECT · UPDATE · DELETE 구문 / 수업의 정상 (0) | 2020.11.12 |
[생활코딩|PHP Day4] PHP 함수의 사용 / PHP 제어문 예고 (0) | 2020.11.12 |
최근댓글