블로그 이전했습니다. https://jeongzero.oopy.io/
php 기본 문법 정리
본문 바로가기
프로그래밍 관련/Web

php 기본 문법 정리

728x90

(계속 업데이트 할 예정) 

 

1. url 파라미터

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    안녕하세요. <?php echo $_GET['address']; ?>에 사시는 <?php echo $_GET['name']; ?>님
  </body>
</html>

 

2. 조건문

<h2>
      <?php
      if(isset($_GET['id'])){
        echo $_GET['id'];
      } else {
        echo "Welcome";
      }
      ?>
</h2>
  • 기본적인 형태는 C언어와 동일. url 파라미터가 존재하는지 확인하는 함수 isset()

 

3. 함수

<?php
function print_title()
{
  $index=0;
  $list=scandir("./data");
  while( $index < count($list))
  {
     if($list[$index]!='.' and $list[$index]!='..')
     {
       echo "<li><a href=\"index.php?id=$list[$index]\">$list[$index]</a></li>";
     }
     $index=$index+1;
  }
}
?>
  • 함수는 function 함수명() 이렇게 하면 됨.

 

4.배열

<?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);
?>
  • array() 이거임. 소괄호임.
  • array_push(배열이름, 값)
  • array_pop()
  • array_shift()
  • array_unshfit()

 

5. FORM and POST

<!doctype html>
<html>
  <body>
    <form action="form.php" method="post">
      <p><input type="text" name="title" placeholder="Title"></p>
      <p><textarea name="description"></textarea></p>
      <p><input type="submit"></p>
    </form>
  </body>
</html>
<?php
file_put_contents('data/'.$_POST['title'], $_POST['description']);
?>
  • file_put_contents(파일명, 넣을 데이터)

 

6. 모듈화 관련

<?php
require_once('lib/print.php');
?>
  • require_once() : 공통되는 코드 모듈화.
  • require() 과 다른점은 위에껀 한번만 선언됨

 

7. PHP MySQL API

  • API 종류
    1. mysqli → 함수기반 DB사용
    1. PDO_mysql → 다른 DBMS를 사용할때 php 코드를 바꾸지 않아도 다른 DB 사용 가능. 이건 객체지향 기반 DB 사용
    1. mysql

 

  • mysqli 기반 API 문법
    $conf=mysqli_connect("localhost","root","123123","opentutorials");
    //mysql 연결
    
    $sql="select * from topic";
    //쿼리문
    
    $result=mysqli_query($conf,$sql);
    //설정 값 , 쿼리문 을 인자로 넣으면 result에 쿼리 결과가 담김
    
    $row=mysqli_fetch_array($result)
    //결과값을 php 형식에 맞게 변환. 그 결과가 array 형식으로 $row에 담김.

 

  • 사용법 예시
    while($row=mysqli_fetch_array($result))
    {
      #echo '<li>'.$row['title'].'</li>';
      $escape_title=htmlspecialchars($row['title']);
      $list=$list."<li><a href=\"index.php?id={$row['id']}\">{$escape_title}</a></li>";
    }
    <보안 관련>
    
    1. htmlspecialchars($row['title']);
    		-> 특수 HTML 문자를 엔티티로 변환하여 문제없이 출력 할 수 있도록 함
    
    2. mysqli_real_escape_string($conf,$_GET['id'])
    		-> 민감한 SQL 문자를 이스케이프하므로 SQL 삽입 위험없이 동적 쿼리를 수행 가능
    		-> settype($_POST['id'],'integer'); 이거랑 비슷
    
    즉 1번 함수는 민감한 OUTPUT을, 2번 함수는 민감한 INPUT을 막음
    <에러관련>
    
    $result=mysqli_query($conf,$sql);
    if($result == false){
        echo "error";
        echo (mysqli_error($conf));
        #사용자에게 에러메시지를 안보여주고 관리자가 확인하는 방법
    }
    else{
        echo 'success. <a href="index.php">돌아가기</a>';
        
    }
728x90