Raspberry Pi_Kor_24.4.11 PHP와 MySQL database


Published Book on Amazon


All of IOT Starting with the Latest Raspberry Pi from Beginner to Advanced – Volume 1
All of IOT Starting with the Latest Raspberry Pi from Beginner to Advanced – Volume 2


출판된 한글판 도서


최신 라즈베리파이(Raspberry Pi)로 시작하는 사물인터넷(IOT)의 모든 것 – 초보에서 고급까지 (상)
최신 라즈베리파이(Raspberry Pi)로 시작하는 사물인터넷(IOT)의 모든 것 – 초보에서 고급까지 (하)


Original Book Contents


24.4.11               PHP MySQL database

 

24.4.11.1  PHP MySQL extension

 

PHP에서 MySQL 자료를 처리하는 기능들은 PHP extension으로 개발되어 제공되고 있는데, 지금까지 개발된 extension에는 다음과 같은 것이 있다.  

 

    original MySQL extension

PHP에서 MySQL 자료에 접근하기 위해서 처음 개발된 extension 기능이다. 이것은 원래 MySQL version 4.1.3 이전 시스템에만 적용되는 것을 전제로 개발된 것으로, 그 이후 version에도 적용할 수는 있지만, 최신 MySQL server의 기능을 충분히 활용할 수 없으며, 향후 폐기될 기능이다.

 

    MySQL improved extension (mysqli)

MySQL database의 최신 기능을 완전하게 활용할 수 있도록 object-oriented programming 환경에 맞추어 재개발된 MySQL 처리 extension이다. PHP versions 5 이후에 기능이 포함되어 있다. mysqli extension original MySQL extension에 비해 많은 장점이 있는데, 주요한 것은 다음과 같다.

Object-oriented interface

Support for Prepared Statements

Support for Multiple Statements

Support for Transactions

Enhanced debugging capabilities

Embedded server support

 

    PDO extension

PHP application에게 database abstraction layer를 제공하여 실제 사용하는 database의 종류와 상관없이, 모든 database 관련 기능을 일관되게 동일한 형식으로 활용할 수 있도록 해주는 extension이다. 필요하면 다른 database로 간편하게 교체할 수 있는 이점이 있지만, 특정 database의 모든 기능을 충분히 활용할 수 없는 단점이 있다.   


 

original MySQL extension은 향후 폐기될 예정이므로 향후 새로운 프로그램을 개발할 때는 mysqli extension PDO extension을 사용해야 한다

 

추가적인 정보에 대해서는 다음을 참고하기 바란다.

    http://php.net/manual/en/set.mysqlinfo.php

 

 

 


 

24.4.11.2  <mysqli>interface 방식

 

<mysqli> extensionobject-oriented interface 방식과 함께 procedural interface 방식도 함께 지원한다. 다음은 object-oriented interface 방식과 procedural interface 방식에 대한 사례를 보여 주는 것이다.

 

<?php

 

//=========================================

//====== procedural interface

//=========================================

$mysqli = mysqli_connect("example.com", "user", "password", "database");

if (mysqli_connect_errno($mysqli)) {

    echo "Failed to connect to MySQL: " . mysqli_connect_error();

}

 

$res = mysqli_query($mysqli, "SELECT 'A world full of ' AS _msg FROM DUAL");

$row = mysqli_fetch_assoc($res);

echo $row['_msg'];

 

//=========================================

//====== object-oriented interface

//=========================================

$mysqli = new mysqli("example.com", "user", "password", "database");

if ($mysqli->connect_errno) {

    echo "Failed to connect to MySQL: " . $mysqli->connect_error;

}

 

$res = $mysqli->query("SELECT 'choices to please everybody.' AS _msg FROM DUAL");

$row = $res->fetch_assoc();

echo $row['_msg'];

 

?>

 

위 예제의 출력은 아래와 같다

 

A world full of choices to please everybody.

 


 

두 방식에 대한 사용법 상의 차이점은 다음과 같다.

 

작업

Object-oriented

Procedural

object 생성할 때

new mysqli ( )

mysqli_connect ( )

함수를 실행할 때

$object->function( )

mysqli_function($object, )

arrtibute를 참조할 때

$object->attribute

mysqli_attribute($object)

 

기본적으로 object-oriented 방식이 object를 중심으로 function attribute를 체계적으로 분류하여 관리해 주기 때문에 이해하기 쉽고, 개발과 사후 관리에 여러 가지 장점이 있다. 두 방식 사이에는 성능의 차이는 없고, 사용자는 각자의 선호에 따라 원하는 것을 자유롭게 선택할 수 있다. 또한 한 문서에 양쪽 방식을 혼합해서 사용할 수는 있지만, 코드를 이해하기 쉽도록 만들기 위해서는 추천하지 않는다.

 

 


 

24.4.11.3  <mysqli> object-oriented interface 상세

 

여기서는 <mysqli> object-oriented interface property method에 대해서 상세히 설명하도록 한다.

 

   "mysqli" class property and method

 

MySQL database에 있는 자료를 이용하려면, 먼저 해당 database에 접속해야 한다. 또한 database에 있는 자료를 이용한 하는 과정에서도 접속은 계속 유지되어야 한다. 이렇게 지정된 MySQL database에 대한 접속을 담당하는 것이 "mysqli connect"이다. 이것은 또한 향후 모든 SQL 처리에서 MySQL과의 연동을 담당한다.

 

"mysqli" class는 이러한 "mysqli connect"를 관리하고 처리하는 역할을 하는 object class로서, 반드시 미리 object로 생성한 다음 사용해야 한다.

 

class에서 사용할 수 있는 property method은 다음과 같다.  

 

OOP Interface

Description

Properties

$mysqli::affected_rows

Gets the number of affected rows in a previous MySQL operation

$mysqli::client_info

Returns the MySQL client version as a string

$mysqli::client_version

Returns MySQL client version info as an integer

$mysqli::connect_errno

Returns the error code from last connect call

$mysqli::connect_error

Returns a string description of the last connect error

$mysqli::errno

Returns the error code for the most recent function call

$mysqli::error

Returns a string description of the last error

$mysqli::field_count

Returns the number of columns for the most recent query

$mysqli::host_info

Returns a string representing the type of connection used

$mysqli::protocol_version

Returns the version of the MySQL protocol used

$mysqli::server_info

Returns the version of the MySQL server

$mysqli::server_version

Returns the version of the MySQL server as an integer

$mysqli::info

Retrieves information about the most recently executed query

$mysqli::insert_id

Returns the auto generated id used in the last query

$mysqli::sqlstate

Returns the SQLSTATE error from previous MySQL operation

$mysqli::warning_count

Returns the number of warnings from the last query for the given link

Methods

mysqli::autocommit()

Turns on or off auto-committing database modifications

mysqli::change_user()

Changes the user of the specified database connection

mysqli::character_set_name(), mysqli::client_encoding

Returns the default character set for the database connection

mysqli::close()

Closes a previously opened database connection

mysqli::commit()

Commits the current transaction

mysqli::__construct()

Open a new connection to the MySQL server [Note: static (i.e. class) method]

mysqli::debug()

Performs debugging operations

mysqli::dump_debug_info()

Dump debugging information into the log

mysqli::get_charset()

Returns a character set object

mysqli::get_connection_stats()

Returns client connection statistics. Available only with mysqlnd.

mysqli::get_client_info()

Returns the MySQL client version as a string

mysqli::get_client_stats()

Returns client per-process statistics. Available only with mysqlnd.

mysqli::get_cache_stats()

Returns client Zval cache statistics. Available only with mysqlnd.

mysqli::get_server_info()

NOT DOCUMENTED

mysqli::get_warnings()

NOT DOCUMENTED

mysqli::init()

Initializes MySQLi and returns a resource for use with mysqli_real_connect. [Not called on an object, as it returns a $mysqli object.]

mysqli::kill()

Asks the server to kill a MySQL thread

mysqli::more_results()

Check if there are any more query results from a multi query

mysqli::multi_query()

Performs a query on the database

mysqli::next_result()

Prepare next result from multi_query

mysqli::options()

Set options

mysqli::ping()

Pings a server connection, or tries to reconnect if the connection has gone down

mysqli::prepare()

Prepare an SQL statement for execution

mysqli::query()

Performs a query on the database

mysqli::real_connect()

Opens a connection to a mysql server

mysqli::real_escape_string(), mysqli::escape_string()

Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

mysqli::real_query()

Execute an SQL query

mysqli::refresh()

Flushes tables or caches, or resets the replication server information

mysqli::rollback()

Rolls back current transaction

mysqli::select_db()

Selects the default database for database queries

mysqli::set_charset()

Sets the default client character set

mysqli::set_local_infile_default()

Unsets user defined handler for load local infile command

mysqli::set_local_infile_handler()

Set callback function for LOAD DATA LOCAL INFILE command

mysqli::ssl_set()

Used for establishing secure connections using SSL

mysqli::stat()

Gets the current system status

mysqli::stmt_init()

Initializes a statement and returns an object for use with mysqli_stmt_prepare

mysqli::store_result()

Transfers a result set from the last query

mysqli::thread_id()

Returns the thread ID for the current connection

mysqli::thread_safe()

Returns whether thread safety is given or not

mysqli::use_result()

Initiate a result set retrieval

24‑1 "mysqli" class property method


 

   "mysqli_stmt" class property and method

 

"mysqli statement" SQL 문장이 실제로 실행을 하기 전에 database의 현재 상태에 따라 가장 효율적으로 실행될 수 있도록 사전에 prepare SQL 문을 의미한다. 이렇게 prepareSQL 문을 이용하면, SQL 문을 실행하기 전에 SQL 문의 문제점을 확인하고, SQL문을 효율적으로 수행할 수 있는 준비작업을 할 수 있다.

 

"mysqli_stmt" class는 이런 "mysqli statement"를 관리하고 처리하는 역할을 하는 object class로서, 반드시 미리 object로 생성한 다음 사용해야 한다.

 

class에서 사용할 수 있는 propertymethod는 다음과 같다.

 

OOP Interface

Description

Properties

$mysqli_stmt::affected_rows

Returns the total number of rows changed, deleted, or inserted by the last executed statement

$mysqli_stmt::errno

Returns the error code for the most recent statement call

$mysqli_stmt::error

Returns a string description for last statement error

$mysqli_stmt::field_count

Returns the number of field in the given statement - not documented

$mysqli_stmt::insert_id

Get the ID generated from the previous INSERT operation

$mysqli_stmt::num_rows

Return the number of rows in statements result set

$mysqli_stmt::param_count

Returns the number of parameter for the given statement

$mysqli_stmt::sqlstate

Returns SQLSTATE error from previous statement operation

Methods

mysqli_stmt::attr_get()

Used to get the current value of a statement attribute

mysqli_stmt::attr_set()

Used to modify the behavior of a prepared statement

mysqli_stmt::bind_param()

Binds variables to a prepared statement as parameters

mysqli_stmt::bind_result()

Binds variables to a prepared statement for result storage

mysqli_stmt::close()

Closes a prepared statement

mysqli_stmt::data_seek()

Seeks to an arbitrary row in statement result set

mysqli_stmt::execute()

Executes a prepared Query

mysqli_stmt::fetch()

Fetch results from a prepared statement into the bound variables

mysqli_stmt::free_result()

Frees stored result memory for the given statement handle

mysqli_stmt::get_result()

Gets a result set from a prepared statement. Available only with mysqlnd.

mysqli_stmt::get_warnings()

NOT DOCUMENTED

$mysqli_stmt::more_results()

NOT DOCUMENTED Available only with mysqlnd.

$mysqli_stmt::next_result()

NOT DOCUMENTED Available only with mysqlnd.

mysqli_stmt::num_rows()

See also property $mysqli_stmt::num_rows

mysqli_stmt::prepare()

Prepare an SQL statement for execution

mysqli_stmt::reset()

Resets a prepared statement

mysqli_stmt::result_metadata()

Returns result set metadata from a prepared statement

mysqli_stmt::send_long_data()

Send data in blocks

mysqli_stmt::store_result()

Transfers a result set from a prepared statement

24‑2 "mysqli_stmt" classproperty method

 


 

   mysqli_result properties and method

 

"mysqli result" SQL SELECT문을 실행한 결과로 만들어지는 query result로서 특정 database의 지정 table들에서 조회되는 여러 개의 row로 구성되는 data set을 의미한다. 여기서 조회되는 각각의 row는 또 다시 복수의 column으로 구성되어 있다.  

 

"mysqli_result" class는 이런 "mysqli result"를 관리하고 처리하는 역할을 하는 object class로서, 반드시 미리 object로 생성한 다음 사용해야 한다.

 

class에서 사용할 수 있는 propertymethod는 다음과 같다.

 

OOP Interface

Description

Properties

$mysqli_result::current_field

Get current field offset of a result pointer

$mysqli_result::field_count

Get the number of fields in a result

$mysqli_result::lengths

Returns the lengths of the columns of the current row in the result set

$mysqli_result::num_rows

Gets the number of rows in a result

Methods

mysqli_result::data_seek()

Adjusts the result pointer to an arbitrary row in the result

mysqli_result::fetch_all()

Fetches all result rows and returns the result set as an associative array, a numeric array, or both. Available only with mysqlnd.

mysqli_result::fetch_array()

Fetch a result row as an associative, a numeric array, or both

mysqli_result::fetch_assoc()

Fetch a result row as an associative array

mysqli_result::fetch_field_direct()

Fetch meta-data for a single field

mysqli_result::fetch_field()

Returns the next field in the result set

mysqli_result::fetch_fields()

Returns an array of objects representing the fields in a result set

mysqli_result::fetch_object()

Returns the current row of a result set as an object

mysqli_result::fetch_row()

Get a result row as an enumerated array

mysqli_result::field_seek()

Set result pointer to a specified field offset

mysqli_result::free(), mysqli_result::close, mysqli_result::free_result

Frees the memory associated with a result

24‑3 "mysqli_result" class property and method

24.4.11.4  [mysqli] Object-oriented interface 사용법 

 

PHP에서 MySQL database에 있는 자료를 참조하기 위해서는 사전에 해당 database에 접속(connect)되어 있어야 한다.

 

 

   "connect" object 생성

 

MySQL database connect 하기 위해서는 먼저 database 접속정보를 이용하여 connect 작업을 수행해서 object를 생성한 다음, database에 대한 connect 정보를 "connect" object에 보관해 둔다. 나중에 실제로 database의 자료를 참조하기 위해서 SQL 문장을 수행할 필요가 있을 때는 앞에서 생성한 "connect" object를 통하여 SQL 문장을 실행하는 것이다.    

 

MySQL database에 접속하기 위해서는 "mysqli( )" 함수를 실행하고, "new" 명령을 사용하여 object를 생성하여 "connect" object 변수에 connect 정보를 저장한다. 기본적인 형식은 다음과 같다.

 

$connect_object = new  mysqli( host-nameuser-id , password , database-name  )  

 

 

   database 자료 조회 SQL 실행 

 

MySQL database에 대해서 특정 SQL 문장을 처리할 경우는 "query( )" 함수를 사용한다. "query( )" 함수는 SQL 문장의 실행 결과를 되돌려 주는데, "result object"라는 형태의 object로 결과를 되돌려준다. 기본적인 처리 형식은 다음과 같다.

 

$result_object =  $connect_object->query(  "SELECT-SQL"  )

 


 

   조회된 database 자료 처리

 

"result" object에는 여러 개의 자료가 함께 포함되어 있을 수 있다. "fetch_assoc( )" 함수를 이용하면, "result" object에 포함되어 있는 자료를 순차적으로 하나씩 되돌려 주는데, "row" object라는 형태의 object로 결과를 되돌려 준다. 기본적인 처리형식은 다음과 같다.

 

$row_object =  $result_object->fetch_assoc(  )

 

"row" object에는 여러 개의 column에 대한 자료가 함께 포함되어 있다. 각각의 column에 대한 자료를 참조하고자 하면 ["column-name"] 형식으로 column을 지정한다. 기본적인 처리형식은 다음과 같다.

 

$data-variable    = $row_object["column-name"]

 

통상적으로 "result" object에는 여러 개의 자료가 있으므로 순차적으로 반복적인 처리를 위해서 보통 "while" 명령을 사용하여 다음과 같이 처리한다.

 

while  ( $row_object =  $result_object->fetch_assoc( )  )

      {

           statement-1   ;

           statement-2   ;

      }

 

 

   "connect" 종료 

 

더 이상 database 접속이 필요 없을 때는 다음과 같이 "close( )" 함수를 사용하여 "connect"를 종료시켜야 한다. 기본적인 처리 형식은 다음과 같다.

 

$connect_object->close( )

 


 

Leave a Reply