我正在将表单数据插入数据库。
我的问题是只能填充一列,而第二列仍为空(允许为空)。
通过以下代码,我可以将数据插入wp_my_table
,但只能插入1列。我在做什么错了?
我还如何插入Datepicker以便从下拉菜单中选择某些值?
function elh_insert_into_db() {
global $wpdb;
// creates my_table in database if not exists
$table = $wpdb->prefix . "my_table";
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`Desc` text NULL,
UNIQUE (`id`)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
// starts output buffering
ob_start();
?>
<form action="" method="post" id="v_form">
<label for="visitor_name"><h3>Hello there! What is your name?</h3>
</label>
<input type="text" name="visitor_name" id="visitor_name" value="" />
<input type="text" name="Desc" id="Desc" value="?php echo $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["visitor_name"] != "" ) {
global $wpdb;
$table = $wpdb->prefix."my_table";
$data=array(
'name'=> $_POST['visitor_name'] ,
'Desc'=> $_POST['Desc']
);
$wpdb->insert($table,$data);
$wpdb->show_errors();
$wpdb->print_error();
$html = "<p>Your name <strong>$name</strong> was successfully recorded.
Thanks!!</p>";
}
// if the form is submitted but the name is empty
if ( isset( $_POST["submit_form"] ) && $_POST["visitor_name"] == "" )
$html .= "<p>You need to fill the required fields.</p>";
// outputs everything
return $html;
}
// adds a shortcode you can use: [insert-into-db]
add_shortcode('elh-db-insert', 'elh_insert_into_db');