2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【MySQL】MySQL5.7をWordpressに組み込んでJSON型を使ってみる

Last updated at Posted at 2016-06-30

#【MySQL】MySQL5.7をWordpressに組み込んでJSON型を使ってみる
MySQL5.7から速度もアップしてJSON型が使用できるようになったということで、Wordpressを絡めて使用した時のメモ。今回は独自テーブルをJSON型を含む形で作成し、post_idでwp_postと紐付けて投稿内容をそこに格納してみる。

・JSON型を含むテーブルをCREATE

CREATE TABLE wp_my_meta (
          id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
          json_val json DEFAULT NULL,
          modified_date datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          create_date datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
          UNIQUE KEY id (id)
        )
        CHARACTER SET 'utf8';

こんな感じで。

・データのインサート

$temp_json_val = フォームのPOST値など(テストなら別に空でもいい);
$temp_json_val['post_id'] = $post_id;
$temp_json_val['post_type'] = $_POST['post_type'];
$temp_json_val['post_title'] = $_POST['post_title'];
$wpdb->insert( 'wp_my_meta', array('json_val' => json_encode($temp_json_val)));

これでインサートできる。

・データのアップデート

//更新するデータのid
$get_id = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT id
                  FROM wp_my_meta
                   WHERE json_extract(json_val,'$.post_id') = " .$post_id)
        );
$temp_json_val = フォームのPOST値など(テストなら別に空でもいい);
$temp_json_val['post_id'] = $post_id;
$temp_json_val['post_type'] = $_POST['post_type'];
$temp_json_val['post_title'] = $_POST['post_title'];
$wpdb->update( 'wp_my_meta', array('json_val' => json_encode($temp_json_val)), array('id' => $get_id));

アップデート完了。

とりあえずここまでメモ。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?