====== Handling database access in a Wordpress plugin ====== [[https://codex.wordpress.org/Class_Reference/wpdb|Wpdb class]] [[https://developer.wordpress.org/reference/classes/wpdb/|BIS]] [[https://codex.wordpress.org/Data_Validation#Database|Data validation for SQL]] === Get many data === global $wpdb; $sql = "SELECT * FROM " . $wpdb->prefix . "table_name"; $result = $wpdb->get_results( $sql ); [[https://developer.wordpress.org/reference/classes/wpdb/get_results/|get_results($query, $output)]] === 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'); [[https://developer.wordpress.org/reference/classes/wpdb/get_row/|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 . '
'; if($result == 0) { // echo 'No table found, creating it...
'; $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 . '
'; $sql = "ALTER TABLE `" . $wpdb->prefix . "table_name` ADD PRIMARY KEY (`id_table_name`);"; $result = $wpdb->query( $sql ); // echo $sql . ' = ' . $result . '
'; $sql = "ALTER TABLE `" . $wpdb->prefix . "table_name` MODIFY `id_service_technique` int(11) NOT NULL AUTO_INCREMENT;"; $result = $wpdb->query( $sql ); // echo $sql . ' = ' . $result . '
'; } }