WordPress使用简码将数据从前端插入到自定义表



我正在尝试通过从插件创建一个新表将数据插入WordPress数据库。我使用简码来生成我创建表格的表单,但是当我尝试从表单插入数据时,它不会插入数据。有人可以帮助我吗?

这是我的代码:-

function insert_into_employee_db() {
global $wpdb;
$page_link = get_permalink();
// starts output buffering
ob_start();
?>
<style>
form#v_form>input {
margin: 5px;
}
</style>
<form action="" method="post" id="v_form">
<input type="text" name="total_employee" id="total_employee" placeholder="Total Employee" />
<input type="text" name="present_employee" id="present_employee" placeholder="Present Today" />
<input type="text" name="br_manager" id="br_manager"  placeholder="Manager Name"/>
<input type="number" name="br_code" id="br_code"  placeholder="Branch Code"/>
<input type="text" name="br_name" id="br_name"  placeholder="Branch Name"/>
<input type="submit" name="submit_form" value="submit" />
</form>
<?php
$html = ob_get_clean();
// does the inserting, in case the form is filled and submitted
if ( isset( $_POST["submit_form"] ) && $_POST["total_employee"] != "" ) {
$tablename = $wpdb->prefix."sbl_employee";
$time               = date("d/m/Y");
$total_employee     = $_POST["total_employee"];
$present_employee   = $_POST["present_employee"];
$br_manager         = $_POST["br_manager"];
$br_code            = $_POST["br_code"];
$br_name            = $_POST["br_name"];
$data = array(
'time'              => date('dd-mm-YY'),
'total_employee'    => (int)$total_employee,
'present_employee'  => (int)$present_employee,
'br_manager'        => $br_manager,
'br_code'           => (int)$br_code,
'br_name'           => $br_name,
);

$format = array(
'%s', '%s', '%s', '%s', '%s', '%s'
);
$success=$wpdb->insert( $tablename, $data, $format );
if($success){
$html = "<p>Successfully Saved. <a href=".$page_link.">Update? </a></p>";
}else{
$html = "failed. ". $wpdb->show_errors();
}
}
// if the form is submitted but the name is empty
if ( isset( $_POST["submit_form"] ) && $_POST["total_employee"] == "" )
$html .= "<p>You need to fill the required fields.</p>";
// outputs everything
return $html;
}
// adds a shortcode you can use: [insert-employee]
add_shortcode('insert_employee', 'insert_into_employee_db');

这是我的数据库创建函数

function sbl_employee_create_db() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_employee  = $wpdb->prefix . 'sbl_employee';
$table_br_name   = $wpdb->prefix . 'sbl_br_name';
$sql = "CREATE TABLE IF NOT EXISTS $table_employee (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
total_employee smallint(5) NOT NULL,
present_employee smallint(5) NOT NULL,
br_manager varchar(5) NOT NULL,
br_code smallint(5) NOT NULL,
br_name varchar(120) NOT NULL,
UNIQUE KEY id (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
//do action when plugin active
register_activation_hook( __FILE__, 'sbl_employee_create_db' );

试试这种格式,让我知道新格式会发生什么?

$format = array(
'%s', '%d', '%d', '%s', '%d', '%s'
);

最新更新