WordPress wpdb CRUD example
워드프레스에서 wpdb를 사용한 CRUD 작업 예
http://codex.wordpress.org/Class_Reference/wpdb#Interfacing_With_the_Database
https://codex.wordpress.org/Class_Reference/wpdb
워드프레스에서 제공하는 wpdb 클래스는 워드프레스가 관리하는 데이터베이스에 접속하여 데이터 입출력 작업을 쉽게 할 목적으로 사용되지만 다른 데이터베이스에도 사용할 수 있다
wpdb 오브젝트에 접근하기
global $wpdb : global 오브젝트 변수로 선언하고 사용하는 방법
$GLOBALS['wpdb'] : superglobal 인 $GLOBALS['wpdb']를 사용할 때는 선언할 필요가 없다
/wp-include/wp-db.php에 정의되어 있다
디폴트로 워드프레스가 관리하는 데이터베이스에 접속되어 있다
global $wpdb, $GLOBAL['wpdb'] 사용 예
// 1st Method - Declaring $wpdb as global and using it to execute an SQL query statement that returns a PHP object
global $wpdb;
$results = $wpdb->get_results( 'SELECT * FROM wp_options WHERE option_id = 1', OBJECT );
// 2nd Method - Utilizing the $GLOBALS superglobal. Does not require global keyword ( but may not be best practice )
$results = $GLOBALS['wpdb']->get_results( 'SELECT * FROM wp_options WHERE option_id = 1', OBJECT );
워드프레스가 디폴트로 생성한 테이블 뿐만이 아니라 개발자가 생성한 테이블에도 다음과 같이 사용할 수 있다
$myrows = $wpdb->get_results( "SELECT id, name FROM mytable" );
여기서는 global #wpdb 를 사용하여 CRUD 작업을 수행하는 플러그인을 작성해 보고자 한다
<?php /* Plugin Name: KCW WPDB CRUD Plugin Plugin URI: http://micropilot.tistory.com Description: WPDB를 이용한 CRUD 테스트 플러그인. Version: 1.0 Author: Kim Chang Woon Author URI: http://micropilot.tistory.com */ //화면에 guest 리스트를 보여주는 함수. Shortcode [kcw_wpdb_show_list]를 페이지 템플릿에 추가하면 됨 add_shortcode('kcw_wpdb_show_list', 'kcw_show_guest_list'); function kcw_show_guest_list($atts){ global $wpdb; $rs = $wpdb->get_results('SELECT id, firstname FROM myguests LIMIT 0, 10'); // 처음부터 10개만 echo '<table>'; echo '<tr><th>아이디</th><th>First Name</th></tr>'; foreach($rs as $guest){ echo "<tr><td> $guest->id </td><td> "; echo "<a href=../guest-desc?id=$guest->id>$guest->firstname</a>"; echo "</td></tr>"; } echo '</table>'; echo "[<a href=../guest-add>추 가</a>]"; } //화면에 guest의 상세정보를 출력하는 함수. Shortcode [kcw_guest_info] add_shortcode('kcw_guest_info', 'kcw_show_guest_info'); function kcw_show_guest_info($atts) { $id = $_GET['id']; global $wpdb; $row = $wpdb->get_row('SELECT id, firstname, lastname, email, reg_date '. "FROM myguests WHERE id=$id"); echo "<table><th>아이디</th><th>FirstName</th><th>LastName</th><th>Email</th><th>Reg-Date</th></tr>"; echo "<tr><td>$row->id</td><td>$row->firstname</td><td>$row->lastname</td>"; echo "<td>$row->email</td><td>$row->reg_date</td></tr>"; echo "</table>"; echo "[<a href=../guest-edit-form?id=$row->id>수 정</a>]"; echo "[<a href=".get_admin_url()."admin-post.php?action=guest_delete&id=$row->id>삭 제</a>]"; echo "[<a href=../guest-list/>목 록</a>]"; } // guest 입력폼을 보여주는 함수 Short[kcw_guest_add_form] add_shortcode('kcw_guest_add_form','kcw_show_add_form'); function kcw_show_add_form($atts){ ?> <form action="<?php echo get_admin_url().'/admin-post.php';?>" method="post"> <input type="hidden" name="action" value="guest_save"> First Name <input type="text" name="firstname" value=""><br> Last Name <input type="text" name="lastname" value=""><br> Email <input type="text" name="email" value="myemail@google.com"><br> <button type="submit">저 장</button> </form> <?php } // guest추가 폼에서 서버측에 guest_save 액션을 전송하면 실행되는 액션함수 add_action('admin_post_guest_save', 'kcw_guest_save'); function kcw_guest_save(){ $fn = $_POST['firstname']; $ln = $_POST['lastname']; $email = $_POST['email']; global $wpdb; $n = $wpdb->insert( 'myguests', array( 'firstname' => $fn, 'lastname' => $ln, 'email' => $email ) ); $id = $wpdb->insert_id; wp_redirect(plugins_url()."/guest-desc?id=$id"); } // guest 수정 폼 Shortcode [kcw_guest_edit_form] add_shortcode('kcw_guest_edit_form', 'kcw_guest_edit_form'); function kcw_guest_edit_form($atts){ $id = $_GET['id']; global $wpdb; $guest = $wpdb->get_row("SELECT * FROM myguests WHERE id=$id"); ?> <form action="<?php echo get_admin_url().'/admin-post.php';?>" method="post"> <input type="hidden" name="action" value="guest_update"> <input type="hidden" name="id" value="<?php echo $id;?>"> First Name <input type="text" name="firstname" value="<?php echo $guest->firstname;?>"><br> Last Name <input type="text" name="lastname" value="<?php echo $guest->lastname;?>"><br> Email <input type="text" name="email" value="<?php echo $guest->email;?>"><br> <button type="submit">저 장</button> </form> <?php } //프런트 엔드에서 수정폼을 전송하면 실행되는 액션함수 add_action('admin_post_guest_update', 'kcw_guest_update'); function kcw_guest_update(){ $id = $_POST['id']; $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $email = $_POST['email']; global $wpdb; $n = $wpdb->update('myguests', array( 'firstname'=>$firstname, 'lastname'=>$lastname, 'email'=>$email), array('id'=>$id)); wp_redirect(plugins_url()."/guest-desc?id=$id"); } //guest-desc 페이지에서 [삭제] 링크를 누르면 호출되는 액션함수 add_action('admin_post_guest_delete', 'kcw_guest_delete'); function kcw_guest_delete(){ $id = $_GET['id']; global $wpdb; $n = $wpdb->delete('myguests', array('id'=>$id)); wp_redirect(plugins_url()."/guest-list"); } ?>