我试图在数据库中插入一些数据,这些数据将从表单接收,但$wpdb的数组是空的。WordPress没有报告任何错误,但记录尚未插入。此页面不在管理面板中。我在一个名为假日列表的页面中添加了这段代码,方法是在插件激活时创建一段短代码。
下面是代码。
<?php
function form_creation(){
global $table_prefix, $wpdb;
$table_name = $table_prefix . "holiday";
$state_table= $table_prefix . "state";
?>
<div>
<h2>Holiday List</h2>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["submit"])){
?>
<h2>Add Holiday</h2>
<form name="add-form" action="<?php echo get_home_url(); ?>/holiday-list" method="POST">
<input type="text" name="holiday_name" placeholder="Name of the Holiday" required>
<input type="date" name="date" placeholder="select date" required>
<select name="state_form_select" required>
<option value="none">None</option>
<?php
$results = $wpdb->get_results( "SELECT id,state_name FROM $state_table ORDER BY state_name ASC"); // Query to fetch data from database table and storing in $results
foreach($results as $row){
?>
<option value="<?php echo $row->id; ?>"><?php echo $row->state_name; ?></option>;
<?php
}
?>
</select>
<input type="submit" name="state_submit">
</form>
<?php
}
else if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["state_submit"])){
$holiday_name = $_POST[\'holiday_name\'];
$date = $_POST[\'date\'];
$state_form_select = $_POST[\'state_form_select\'];
$wpdb->insert(
$table_name,
array(
\'holiday_name\' => $holiday_name,
\'date\' => $date,
\'state\' => $state_form_select,
)
);
$success = $wpdb->insert($table_name, array(
"holiday_name" => $holiday_name,
"date" => $date,
"state" => $state_form_select,
));
if($success) {
echo $success;
echo \' Inserted successfully\';
} else {
echo \'not\';
}
}
else{
echo $table_name;
?>
<form name="add-button" action="http://connect.narayanbhargavagroup.loc/holiday-list/" method="POST">
<input type="submit" name="submit" value="Add Holiday">
</form>
<table width="100%" border="1" cellpadding="5" cellspacing="0">
<thead>
<tr>
<td>Sr.No</td>
<td>Holiday</td>
<td>Date</td>
<td>Day</td>
<td>State</td>
</tr>
</thead>
<tbody>
<tr>
<?php
$results = $wpdb->get_results( "SELECT * FROM $table_name"); // Query to fetch data from database table and storing in $results
foreach($results as $row){
?>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->holiday_name;?> </td>
<td><?php echo $row->date; ?></td>
<td><?php echo $row->day; ?></td>
<td><?php echo $row->states; ?></td>
<?php
}
?>
</tr>
</tbody>
</thead>
</table>
</div>
<?php
}
}
add_shortcode(\'test\', \'form_creation\');
下面是我使用的create table语法代码,以便理解表结构。
CREATE TABLE `connect_holiday` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`holiday_name` varchar(250) NOT NULL,
`date` varchar(128) NOT NULL,
`day` varchar(50) NOT NULL,
`states` varchar(250) NOT NULL,
`addedby` varchar(250) NOT NULL,
`added_on` varchar(250) NOT NULL,
`last_edited_by` varchar(250) NOT NULL,
`timestamp` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;