본 게시글은 유튜브 생활코딩 온라인강의를 시청한 후 학습한 정보를 기록하는 목적의 게시글입니다.

생각의 흐름에 따라 작성된 게시글입니다. 가독성이 떨어질 수 있습니다.

생활코딩 유튜브

 

생활코딩

일반인에게 프로그래밍을 알려주는 온라인/오프라인 활동 입니다.

www.youtube.com

생활코딩 사이트

 

생활코딩

hello world 생활코딩의 세계에 오신 것을 환영합니다. 생활코딩은 일반인들에게 프로그래밍을 알려주는 무료 온라인, 오프라인 수업입니다.  어떻게 공부할 것인가를 생각해보기 전에 왜 프로그래밍을 공부하는 이유에 대한 이유를 함께 생각해보면 좋을 것 같습니다. 아래 영상을 한번 보시죠. 온라인 강의 소개 입문자의 가장 큰 고충은 '무엇을 모르는지 모르는 상태'일 겁니다. 온라인에는 프로그래밍을 익히는 데 필요한 거의 모든 정보가 있지만, 이 지식들은

opentutorials.org

생활코딩 WEP3 PHP & MySQL을 수강하기 위한 선수과목인

WEB2 - PHPDATABASE2 - MySQL에 대한 수강 기록입니다.

수강 일정은 야학의 수강계획표에 따릅니다.


#1.

함수의 사용자로서 함수가 무엇인가? 함수를 어떻게 사용하는가?

필요한 함수를 어떻게 찾을 수 있는가를 살펴보는 시간입니다.

 

다른 사람이 만든 함수를 PHP에서 사용하는 방법을 알아보자.

<!DOCTYPE html>
<html>
  <head>
    <title>Function</title>
  </head>
  <body>
    <h1>Function</h1>
    <?php
    $str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    echo $str;
     ?>
  </body>
</html>

만약 위와 같은 코드가 있을 때 우리가 변수 str의 길이가 궁금하다면 어떻게 해야 할까?

여기 공식문서에 그 정답을 찾을 수 있다.

 

PHP: strlen - Manual

I want to share something seriously important for newbies or beginners of PHP who plays with strings of UTF8 encoded characters or the languages like: Arabic, Persian, Pashto, Dari, Chinese (simplified), Chinese (traditional), Japanese, Vietnamese, Urdu, M

www.php.net

<!DOCTYPE html>
<html>
  <head>
    <title>Function</title>
  </head>
  <body>
    <h1>Function</h1>
    <?php
    $str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
     ?>
     <h2>strlen()</h2>
     <?php
     echo strlen($str);
      ?>
  </body>
</html>

strlen 함수를 통해서, Atom 에디터의 Lorem으로 무작위로 생성된 문자열의 길이가 446자임을 알 수 있다.

다른함수에 대해서도 살펴보자.

<!DOCTYPE html>
<html>
  <head>
    <title>Function</title>
  </head>
  <body>
    <h1>Function</h1>
    <?php
    $str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 


    Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    
    echo $str;
     ?>
  </body>
</html>

만약 위 코드처럼 줄바꿈이 일어났을 때 그대로 웹페이지에 반영시키려면 어떻게 해야 할까?

<br>태그를 넣어줌으로써 해결할 수 있겠지만, 쌍따옴표 안에 있는 문자열이기에 쉽지않다.

그럴 때 쓸 수 있는 함수가 nl2br이다.

 

PHP: nl2br - Manual

This is example with "\R" regex token which matches any unicode newline character."u" flag treate strings as UTF-16. Which is optional, depending on your use case. ', $string);}?>NOTE:preg_replace versions are much slower than using str_replace version or

www.php.net

<!DOCTYPE html>
<html>
  <head>
    <title>Function</title>
  </head>
  <body>
    <h1>Function</h1>
    <?php
    $str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.


    Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

    echo nl2br($str);
     ?>
  </body>
</html>

이처럼 자동적으로 <br> 태그를 삽입해 주었음을 알 수 있다.

 

#1-2.

우리가 현재 만들고 있는 프로젝트는 클릭 시 제목만 변경이 되는데,

이를 본문도 바뀔 수 있도록 수정해보자.

이를 위해 data라는 하위폴더를 생성하고,

HTML, CSS, JavaScript란 이름으로 파일 세개를 생성하였다.

이후 클릭이 발생할 때 마다, 제목의 값을 변경해준 것 처럼, 제목의 값과 일치하는 파일을 열어주면 될 텐데

바로 우리가 배운 함수를 사용 할 시간이다.

 

PHP: file_get_contents - Manual

file_get_contents (PHP 4 >= 4.3.0, PHP 5, PHP 7) file_get_contents — Reads entire file into a string Description file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = 0 [, int $maxlen ]]]] ) : string

www.php.net

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>WEB<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
        echo $_GET["id"];
       ?>
    </h2>
    <?php
    echo file_get_contents("data/".$_GET['id']);
     ?>
  </body>
</html>

야호! 이제 글의 내용도 동적으로 변동시킬 수 있다.

하지만, (우리는 php의 설정에서 에러로그를 출력하도록 설정하였기 때문에)

` Notice: Undefined variable: value in ` 이라는 에러를 만날 수 있을 것이다.

물론 클릭을 해서 주소창에 id값이 생긴다면 에러는 금방 사라지지만,

http://127.0.0.1/index.php 의 주소창에서는 에러가 발생할 것이다.

오늘 우리가 배웠던 함수와, 앞으로 배울 가정문을 통해서 이러한 에러를 극복할 수 있다.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>WEB<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>

isset함수를 통해서 'id'가 url에 있을 때만 value라는 변수에 그 갑을 할당하였고,

가정문을 통해서 value에 값이 있을 때만 본문의 내용이 표시되도록 수정하였다.

사실 영상을 보고 단순히 따라 하는 학습도 물론 대단하지만,

의문점이 생긴다면 그 자리에서 바로 해결하는 것이 바람직하다고 생각한다.

생활코딩강의에서 우리는 에러를 만났을 때 어떠한 방식으로 해결할 수 있는지, 그 힘을 배워야 한다.

 

#2.

앞으로 배우게 될 조건문, 반복문이 무엇인가에 대한 예고편입니다. 

 

제어문을 통해서 프로그래밍 된 순서를 제어하는 방법을 알아보도록 하자.

  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기