티거쌤 18강 - 코드이그나이터

aws 가입할것 ( 서버 )

코드 이그나이터
적용법 -> 코드이그나이터 압축해제후 파일,폴더 전체 선택 -> 넷빈즈 SourceFiels 폴더로 드래그



http://localhost/index.php/welcome/ 접속.

사용방법 -

aws -> 가입. ( 호스팅 )

http://codeigniter-kr.org/

제이슨
속성과 값은 콜론으로 구분 : 
pro : value

주소 클래스명 메소드명
http://localhost/index.php/welcome/index/

http://서버주소/index.php/컨트롤러명/메소드명

기본 메소드 문법.

decode아님!!!!!!!! json_decode($json)
echo json_encode($respons_data);


======[ 포스트 방식 ]=================================================

public function get_param(){
           $data1 = $this->input->post("data1");
           $data2 = $this->input->post("data2");
           
           // 배열 선언하여 값을 대입
           $respons_data = array(
               "Data1" => $data1,
               "Data2" => $data2
           );
    
           // ->>decode아님!!!!!!!! json_decode($json)
           // 들어온 값을 출력
           echo json_encode($respons_data);
       }
유니티로 출력할때는 제이슨 파서( json paser )를 설치 해야 한다.
에엣 스토어 boomlagoon json 찾아서 설치.


에엣 스토어 boomlagoon json 찾아서 설치.


warning 메세지 해결법 


 해당 코드 아래 코드로 변경.( 유니티 버전 호환)

유니티 제이슨 파싱 라이브러리 사용 
//JSON 파싱 라이브러리 사용
using Boomlagoon.JSON;









===[ 위 코드 ]========================================================================

using UnityEngine;
using System.Collections;
//JSON 파싱 라이브러리 사용
using Boomlagoon.JSON;
 
public class jsonTest : MonoBehaviour
{
 
    // Use this for initialization
    void Start()
    { 
        StartCoroutine(JsonTest()); 
    }
 
    IEnumerator JsonTest()
    {
 
        string url = "http://localhost/index.php/GameCont/get_param";
 
        WWWForm form = new WWWForm();
        form.AddField("data1""1234");
        form.AddField("data2""abcd");
 
        WWW test = new WWW(url, form);
 
        yield return test;
 
        //기존방법
        Debug.Log(test.text); 
 
        if (test.error == null)
        {
            // 코드이그나이터 제이슨 파서 방법 
            JSONObject json = JSONObject.Parse(test.text);
            string data1 = json.GetString("Data1");
            string data2 = json.GetString("Data2");
            Debug.Log("data1 : " + data1);
            Debug.Log("data1 : " + data2);
        }
        else
        {
            Debug.Log("통신오류"); 
        }
 
    }
 
    // Update is called once per frame
    void Update()
    {
 
    }
}



===[ 코드이그나이터 데이터베이스 접근 ]=====================================================
아래 코드에서 'db_debug' => FALSE, 로 !!

===[ 코드이그나이터 모델생성(조회) ]=====================================================
==[ 코드 ]====================================================
<?php
//게임 데이타 베이스 모델
class GameModel extends CI_Model{
    //테이블명
    var $table = "_user_table";
    //데이터 베이스 객체 참조 변수 (디비명)
    var $user_db;
    // 모델 클래스 생성
    function __construct() {
        parent::__construct();
        //데이터 베이스 로드및 연결
        //키 값은 config 폴더 안의 database.php에 설정한 키 값
        $this->user_db = $this->load->database("user_db",true);
     }
    // 유저 로그인 처리 , controller 에서 받아옴
     function  user_Login($user_id,$user_pw){
         // 유저 로그인 정보 조회
         $sql = "SELECT * FROM _user_table WHERE user_id=? and user_pw=?";
         // 쿼리 바인딩 배열 생성
         $param = array($user_id ,$user_pw);
         // 쿼리 실행 결과 반환
         $query_result = $this->user_db->query($sql, $param);
         
         //조회 결과가 있다면
         if($query_result->num_rows()>0){
             
             foreach($query_result->result() as $row){
                 return $row; // 레코드 정보 라인
             }
         }         
         return null;
     }
}
?>



수업 최종 코드
===================================================
config > database.php


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
 
/*
| -------------------------------------------------------------------
| DATABASE CONNECTIVITY SETTINGS
| -------------------------------------------------------------------
| This file will contain the settings needed to access your database.
|
| For complete instructions please consult the 'Database Connection'
| page of the User Guide.
|
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
|    ['dsn']      The full DSN string describe a connection to the database.
|    ['hostname'] The hostname of your database server.
|    ['username'] The username used to connect to the database
|    ['password'] The password used to connect to the database
|    ['database'] The name of the database you want to connect to
|    ['dbdriver'] The database driver. e.g.: mysqli.
|            Currently supported:
|                 cubrid, ibase, mssql, mysql, mysqli, oci8,
|                 odbc, pdo, postgre, sqlite, sqlite3, sqlsrv
|    ['dbprefix'] You can add an optional prefix, which will be added
|                 to the table name when using the  Query Builder class
|    ['pconnect'] TRUE/FALSE - Whether to use a persistent connection
|    ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
|    ['cache_on'] TRUE/FALSE - Enables/disables query caching
|    ['cachedir'] The path to the folder where cache files should be stored
|    ['char_set'] The character set used in communicating with the database
|    ['dbcollat'] The character collation used in communicating with the database
|                 NOTE: For MySQL and MySQLi databases, this setting is only used
|                  as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7
|                 (and in table creation queries made with DB Forge).
|                  There is an incompatibility in PHP with mysql_real_escape_string() which
|                  can make your site vulnerable to SQL injection if you are using a
|                  multi-byte character set and are running versions lower than these.
|                  Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
|    ['swap_pre'] A default table prefix that should be swapped with the dbprefix
|    ['encrypt']  Whether or not to use an encrypted connection.
|    ['compress'] Whether or not to use client compression (MySQL only)
|    ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections
|                            - good for ensuring strict SQL while developing
|    ['failover'] array - A array with 0 or more data for connections if the main should fail.
|    ['save_queries'] TRUE/FALSE - Whether to "save" all executed queries.
|                 NOTE: Disabling this will also effectively disable both
|                 $this->db->last_query() and profiling of DB queries.
|                 When you run a query, with this setting set to TRUE (default),
|                 CodeIgniter will store the SQL statement for debugging purposes.
|                 However, this may cause high memory usage, especially if you run
|                 a lot of SQL queries ... disable this to avoid that problem.
|
| The $active_group variable lets you choose which connection group to
| make active.  By default there is only one group (the 'default' group).
|
| The $query_builder variables lets you determine whether or not to load
| the query builder class.
*/
//키는 데이터 베이스 이름으로 맞춰 준다.
//$active_group = '데이터베이스키(db명)';
$active_group = 'user_db';
$query_builder = TRUE;
//$db[데이터베이스키]-> 모델에서 사용(model 폴더)
$db['user_db'] = array(
    'dsn'    => '',
    'hostname' => 'localhost'// 데이터 베이스 서버 주소.
    'username' => 'root'// 데이터 베이스 접속 ID
    'password' => 'autoset'//  데이터 베이스 접속 PW
    'database' => 'user_db'//db명 실제 데이터 베이스 db명과 같아야 함
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => FALSE,
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);


===================================================
controllers > GameCont.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
 
class GameCont extends CI_Controller {
 
    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *         http://example.com/index.php/welcome
     *    - or -
     *         http://example.com/index.php/welcome/index
     *    - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see http://codeigniter.com/user_guide/general/urls.html
     */
         
        function __construct() {
            parent::__construct();
            
            //모델 객체를 로드함
            //$this->load->model("클래스명","모델참조변수명");
            $this->load->model("GameModel","game_model");
        }
 
 
        public function index()
    {
            echo 'Game Controller Index!!!';
    }
        
        public function home(){
            echo 'Home!!!';
        }
        
        public function get_param(){            
            $data1 = $this->input->post("data1");
            $data2 = $this->input->post("data2");
            
            $respons_data = array(
                "Data1" => $data1,
                "Data2" => $data2
            );
     
            // ->>decode아님!!!!!!!! json_decode($json)
            echo json_encode($respons_data);
        }
        
        // http://주소/index.php/GameCont/gmae_login
        function game_login(){
            
            $respons_data = array(
            
              // "result_code" => "CODE_0" // CODE_0 : 실패
               // "result" => "FAIL",
               // "result_code" => "0"
            );
            
             $user_id = $this->input->post("user_id");
             $user_pw = $this->input->post("user_pw");
             /*
             if(!($user_id && $user_pw)){
                 $respons_data["code"]="CODE_2";
                 echo json_encode($respons_data);
                 return;                 
             }*/
             
             $result = $this->game_model->user_login($user_id, $user_pw);
             if($result != null){
                 $respons_data["code"]="CODE_1";//성공
             }else{
                 $respons_data["code"]="CODE_0";// 실패
             }
             
             echo json_encode($respons_data);
             // echo $result;
        }
        
        function  user_join(){
               $respons_data = array(
            
              "code" => "CODE_0" // CODE_0 : 실패
               // "result" => "FAIL",
               // "result_code" => "0"
            );
            
             $user_id = $this->input->post("user_id");
             $user_pw = $this->input->post("user_pw");
             /*
             if(!($user_id && $user_pw)){
                 $respons_data["code"]="CODE_2";
                 echo json_encode($respons_data);
                 return;                 
             }*/
             
             $result = $this->game_model->user_join($user_id, $user_pw);
             //join 성공 실패 여부
             if($result != FALSE){
                 $respons_data["code"]="CODE_1";//성공
             }
             
             echo json_encode($respons_data);
             // echo $result;
            
            
        }
       
}


===================================================
models > GameModel.php

<?php
//게임 데이타 베이스 모델
class GameModel extends CI_Model{
    //테이블명
    var $table = "_user_table";
    //데이터 베이스 객체 참조 변수 (디비명)
    var $user_db;
    // 모델 클래스 생성
    function __construct() {
        parent::__construct();
        //데이터 베이스 로드및 연결
        //키 값은 config 폴더 안의 database.php에 설정한 키 값
        $this->user_db = $this->load->database("user_db",true);
     }
    // 유저 로그인 처리 , controller 에서 받아옴
     function  user_Login($user_id,$user_pw){
         // 유저 로그인 정보 조회
         $sql = "SELECT * FROM _user_table WHERE user_id=? and user_pw=?";
         // 쿼리 바인딩 배열 생성
         $param = array($user_id ,$user_pw);
         // 쿼리 실행 결과 반환
         $query_result = $this->user_db->query($sql, $param);
         
         //조회 결과가 있다면
         if($query_result->num_rows()>0){
             
             foreach($query_result->result() as $row){
                 return $row; // 레코드 정보 라인
             }
         }         
         return null;
     }
     function  user_join($user_id,$user_pw){
          // 유저 로그인 정보 조회
         $sql = "INSERT INTO _user_table (user_id, user_pw) VALUES (?, ?)";
         // 쿼리 바인딩 배열 생성
         $param = array($user_id ,$user_pw);
         // 쿼리 실행 결과 반환
         trt
         $query_result = $this->user_db->query($sql, $param);
         
         
         //유저 정보 추가 결과 확인
         if($this->user_db->affected_rows() > 0){
             return TRUE;
         }
         return FALSE;
     }
}
?>


댓글

이 블로그의 인기 게시물

날짜 시간 시간차 시간 계산 하기

코루틴에서 CallBack 함수 적용하기

C++ 언어 퍼센트 구하는 방법 / 기본 언어 퍼센트 구하는 방법