WordPressでSQLを記述してデータベース操作
SELECT 抽出 ( 1レコード )
$sql = “SELECT count(*) as cnt FROM sample_table WHERE post_author = %d”;
$prepared = $wpdb->prepare($sql, esc_sql($user_id));
$post_cnt = $wpdb->get_row($prepared);
return $post_cnt->cnt;
%d,%f,%s(整数,浮動小数点数,文字列)
SELECT 抽出 ( 複数レコード )
$sql = “SELECT * FROM sample_table WHERE post_author = %d”;
$prepared = $wpdb->prepare($sql, esc_sql($user_id));
$posts = $wpdb->get_results($prepared);
if ( $posts ) {
foreach ( $posts as $key => $row ) {
echo $row->ID;
}
}
INSERT 追加
$wpdb->insert( ‘sample_table’,
array( ‘post_author’ => $user_id,’ins_date’ => $data[‘ins_date’] )
);
UPDATE 更新
$wpdb->update( ‘sample_table’,
array( ‘post_author’ => $user_id,’upd_date’ => $data[‘ins_date’] ),
array( ‘id’ => 123 )
);
DELETE 削除
$wpdb->delete( ‘sample_table’,
array( ‘id’ => 123 )
);