Below is a simple, single-file WordPress plugin that:
✔ Creates database table cdat_students on activation
✔ Displays records in admin menu
✔ Provides CRUD operations (Create, Update, Delete)
✔ Uses dashicons for action icons
✔ Uses standard WordPress sanitization + nonce protection
✅ Complete Single-File Plugin: cdat-students.php
<?php
/**
* Plugin Name: CDAT Students Table Creator
* Description: Creates cdat_students table on activation and displays records with shortcode [show_cdat_students].
* Version: 1.0
* Author: RMC
*/
if (!defined('ABSPATH')) exit;
/*===========================================
CREATE TABLE ON PLUGIN ACTIVATION
===========================================*/
function cdat_students_create_table() {
global $wpdb;
$table = $wpdb->prefix . 'cdat_students';
$charset = $wpdb->get_charset_collate();
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$sql = "CREATE TABLE $table (
id INT(11) NOT NULL AUTO_INCREMENT,
roll VARCHAR(20) NOT NULL,
name VARCHAR(200) NOT NULL,
semester INT(2) NOT NULL,
PRIMARY KEY (id)
) $charset;";
dbDelta($sql);
// Insert sample data only if table empty
$count = $wpdb->get_var("SELECT COUNT(*) FROM $table");
if ($count == 0) {
$wpdb->insert($table, array('roll' => '101', 'name' => 'John Doe', 'semester' => 1));
$wpdb->insert($table, array('roll' => '102', 'name' => 'Arun Kumar', 'semester' => 1));
$wpdb->insert($table, array('roll' => '103', 'name' => 'Priya Sharma', 'semester' => 2));
$wpdb->insert($table, array('roll' => '104', 'name' => 'Maria L', 'semester' => 2));
}
}
register_activation_hook(__FILE__, 'cdat_students_create_table');
/*===========================================
SHORTCODE TO DISPLAY STUDENT TABLE
===========================================*/
function cdat_students_display_shortcode() {
global $wpdb;
$table = $wpdb->prefix . 'cdat_students';
$rows = $wpdb->get_results("SELECT * FROM $table ORDER BY semester, roll", ARRAY_A);
if (empty($rows)) {
return "<p>No student records found.</p>";
}
$html = "<h3>CDAT Students</h3>";
$html .= "<table style='width:100%; border-collapse:collapse;'>";
// Header
$html .= "<tr>
<th style='border:1px solid #ccc; padding:6px;'>ID</th>
<th style='border:1px solid #ccc; padding:6px;'>Roll</th>
<th style='border:1px solid #ccc; padding:6px;'>Name</th>
<th style='border:1px solid #ccc; padding:6px;'>Semester</th>
</tr>";
// Rows
foreach ($rows as $r) {
$html .= "<tr>
<td style='border:1px solid #ccc; padding:6px;'>".esc_html($r['id'])."</td>
<td style='border:1px solid #ccc; padding:6px;'>".esc_html($r['roll'])."</td>
<td style='border:1px solid #ccc; padding:6px;'>".esc_html($r['name'])."</td>
<td style='border:1px solid #ccc; padding:6px;'>".esc_html($r['semester'])."</td>
</tr>";
}
$html .= "</table>";
return $html;
}
add_shortcode('show_cdat_students', 'cdat_students_display_shortcode');
No comments:
Post a Comment