Handling database access in a Wordpress plugin
Get many data
Get one row of data
global $wpdb;
$sql = "SELECT id_truc FROM " . $wpdb->prefix . "table_name WHERE id_truc=" . $_GET['id'];
$result = $wpdb->get_row($sql, 'ARRAY_A');
get_row($query, $output, $y)
Get the DB prefix
global $wpdb;
// Current site prefix
echo $wpdb->prefix;
Create table at plugin activation if it don't exist
// If in first plugin file
register_activation_hook( __FILE__ , array($this, 'initDatabase') );
// If not in first plugin file
register_activation_hook( ABSPATH . '/wp-content/plugins/atn/atn.php', array($this, 'initDatabase') );
// ...
public function initDatabase()
{
global $wpdb;
// First check if the table already exist
$sql = "SHOW TABLES LIKE '" . $wpdb->prefix . "table_name'";
$result = $wpdb->query( $sql );
// echo $sql . ' = ' . $result . '<br>';
if($result == 0)
{
// echo 'No table found, creating it...<br>';
$sql = "CREATE TABLE `" . $wpdb->prefix . "table_name` (
`id_table_name` int(11) NOT NULL,
`filename` varchar(255) CHARACTER SET utf8 NOT NULL,
`category` int(11) NOT NULL,
`serial_numbers` text CHARACTER SET utf8 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
$result = $wpdb->query( $sql );
// echo $sql . ' = ' . $result . '<br>';
$sql = "ALTER TABLE `" . $wpdb->prefix . "table_name`
ADD PRIMARY KEY (`id_table_name`);";
$result = $wpdb->query( $sql );
// echo $sql . ' = ' . $result . '<br>';
$sql = "ALTER TABLE `" . $wpdb->prefix . "table_name`
MODIFY `id_service_technique` int(11) NOT NULL AUTO_INCREMENT;";
$result = $wpdb->query( $sql );
// echo $sql . ' = ' . $result . '<br>';
}
}