Latest Post

Hướng dẫn cài đặt Nginx, PHP, MySQL trên Windows 11 và so sánh với Docker Lỗi “Uncaught TypeError: Cannot access offset of type string on string” trong PHP: Nguyên nhân và cách khắc phục

Khi bạn đang phát triển một chủ đề WordPress, quá trình tạo bảng trong cơ sở dữ liệu của WordPress là không thể thiếu. Để thực hiện điều này, bạn có thể sử dụng mã nguồn PHP dưới đây:

Đầu tiên là gọi biến global $wpdb và require file upgrade.php của WordPress:

<?php
global $wpdb;
$dbPrefix = $wpdb->base_prefix;

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

Sau đó gọi function dbDelta với đối số truyền vào là câu lệnh SQL

<?php
dbDeltal('<sql_query_here>');

VD: Tạo 1 bảng CSDL

<?php
global $wpdb;
$dbPrefix = $wpdb->base_prefix;

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

dbDelta("CREATE TABLE `{$dbPrefix}postinfo` (
  `post_id` bigint(20) UNSIGNED AUTO_INCREMENT,
  `is_featured` tinyint(1) UNSIGNED NOT NULL DEFAULT '0',
  `is_hot` tinyint(1) UNSIGNED NOT NULL DEFAULT '0',
  `show_thumbnail` tinyint(3) UNSIGNED NOT NULL DEFAULT '0',
  `source_content` longtext COLLATE utf8mb4_unicode_ci,
  `tutorial_short_title` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `tutorial_level` tinyint(2) UNSIGNED NOT NULL DEFAULT '0',
  PRIMARY KEY (post_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");

Kết quả:

Tạo bảng trong database wordpress
Tạo bảng trong database wordpress

One thought on “Tạo bảng trong Database với WordPress và PHP

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *