Ci-dessous, les différences entre deux révisions de la page.
| Les deux révisions précédentesRévision précédenteProchaine révision | Révision précédente | ||
| webdev:wordpress:plugin_dev:database [28/09/2017 17:12] – dolo | webdev:wordpress:plugin_dev:database [13/10/2017 16:17] (Version actuelle) – dolo | ||
|---|---|---|---|
| Ligne 1: | Ligne 1: | ||
| + | ====== Handling database access in a Wordpress plugin ====== | ||
| + | [[https:// | ||
| + | === Get many data === | ||
| + | <code linenums> | ||
| + | global $wpdb; | ||
| + | $sql = " | ||
| + | $result = $wpdb-> | ||
| + | </ | ||
| + | [[https:// | ||
| + | |||
| + | === Get one row of data === | ||
| + | <code linenums> | ||
| + | global $wpdb; | ||
| + | $sql = " | ||
| + | $result = $wpdb-> | ||
| + | </ | ||
| + | [[https:// | ||
| + | === Get the DB prefix === | ||
| + | <code linenums> | ||
| + | global $wpdb; | ||
| + | |||
| + | // Current site prefix | ||
| + | echo $wpdb-> | ||
| + | </ | ||
| + | |||
| + | ==== Create table at plugin activation if it don't exist ==== | ||
| + | <code linenums> | ||
| + | // If in first plugin file | ||
| + | register_activation_hook( __FILE__ , array($this, | ||
| + | |||
| + | // If not in first plugin file | ||
| + | register_activation_hook( ABSPATH . '/ | ||
| + | |||
| + | // ... | ||
| + | |||
| + | public function initDatabase() | ||
| + | { | ||
| + | global $wpdb; | ||
| + | |||
| + | // First check if the table already exist | ||
| + | $sql = "SHOW TABLES LIKE '" | ||
| + | $result = $wpdb-> | ||
| + | // echo $sql . ' = ' . $result . '< | ||
| + | |||
| + | if($result == 0) | ||
| + | { | ||
| + | // echo 'No table found, creating it...< | ||
| + | $sql = " | ||
| + | `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-> | ||
| + | // echo $sql . ' = ' . $result . '< | ||
| + | |||
| + | $sql = "ALTER TABLE `" . $wpdb-> | ||
| + | ADD PRIMARY KEY (`id_table_name`);"; | ||
| + | $result = $wpdb-> | ||
| + | // echo $sql . ' = ' . $result . '< | ||
| + | |||
| + | $sql = "ALTER TABLE `" . $wpdb-> | ||
| + | MODIFY `id_service_technique` int(11) NOT NULL AUTO_INCREMENT;"; | ||
| + | $result = $wpdb-> | ||
| + | // echo $sql . ' = ' . $result . '< | ||
| + | } | ||
| + | } | ||
| + | </ | ||