Skip to content

Instantly share code, notes, and snippets.

@wolfcoder
Last active June 9, 2022 14:13
Show Gist options
  • Save wolfcoder/442022ab2a186e74e89658280fbf8b13 to your computer and use it in GitHub Desktop.
Save wolfcoder/442022ab2a186e74e89658280fbf8b13 to your computer and use it in GitHub Desktop.
wordpress database management
<?php
global $wpdb;
$tbl = $wpdb->prefix . 'posts';
$post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", 1 ) ); // posts can reference in the phpstorm
$prefix_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $tbl WHERE ID = %d", 1 ) ); // phpstorm: unable to resolve ID
$prepare_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", 1 );
$prepare_result = $wpdb->get_col( $prepare_query ); // 1
// Create table
$custom_tbl = $wpdb->prefix . 'custom_table';
$charset = $wpdb->get_charset_collate();
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( "CREATE TABLE $custom_tbl (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
number smallint(5) NOT NULL DEFAULT 0,
name varchar(60) NOT NULL DEFAULT '',
PRIMARY KEY (id)
) $charset; " );
// Insert to the database
$name = "Bams";
$wpdb->query( "INSERT INTO $custom_tbl ( `number`, `name`) VALUES (5, 'fred')" );
function insert_data($number, $nama) {
global $custom_tbl, $wpdb;
$wpdb->query( $wpdb->prepare( "INSERT INTO $custom_tbl ( `number`, `name`) VALUES (%d, %s)", $number, $nama ) );
}
insert_data(9, 'john');
insert_data(19, 'doe');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment