我正在制作一个带有设置页面的插件。在它的设置页面中,我需要一个只有两个字段的用户注册表:用户名和密码。如何将此数据保存到数据库?
以下是我想做的:
public function PLUGIN_setting_page(){
require_once PLUGIN_PATH. \'templates/admin/plugin-settings.php\';
}
plugin-settins.php
:
<?php
if(isset($_POST[\'submit\'])) {
global $wpdb;
$table = \'wp_myp_user\';
$data = array(
\'username\' => $_POST[\'username\'],
\'password\' => $_POST[\'password\']
);
$format = array(
\'%s\',
\'%s\'
);
$success=$wpdb->insert( $table, $data, $format );
if($success){
echo \'data has been save\' ;
}
}
?>
<div class="login-page">
<div class="form" method="post" action="">
<form class="login-form">
<input type="text" name="ldc_username" placeholder="username" value=""/>
<input type="password" name="ldc_password" placeholder="password" value=""/>
<!-- <button type="submit">login</button> -->
<?php submit_button(); ?>
</form>
</div>
</div>
最合适的回答,由SO网友:Chris Norman 整理而成
代码中几乎没有问题。我做了笔记来帮助解释这些变化。参考资料位于底部,请务必阅读这些参考资料。
//isset is not the correct way. It does not check to see if the post was empty - this is the correct one ($_SERVER..)
if($_SERVER[\'REQUEST_METHOD\'] == \'POST\') {
global $wpdb;
//Make sure this is spelled correct.
$table = \'wp_myp_user\';
//output will check to see if it was posted correctly.
$output = [\'status\' => 1];
//You have to sanitize the fields first - for security reasons.
$username = sanitize_text_field($_POST["ldc_username"]);
$password = sanitize_text_field($_POST["ldc_password"]);
$data = array(
//Make sure this is the same name as in the database - its spelled like this correct?
\'username\' => $username,
\'password\' => $password
);
$format = array(
\'%s\',
\'%s\'
);
//I would not put it in a variable - just send it directly.
$wpdb->insert( $table, $data, $format );
//Here is your post check - to console if it prints 2 - your good.
$output[\'status\'] = 2;
//check reference material to learn more about wp_send_json.
wp_send_json($output);
}
//Previously you were sending it to a function? submit_button(); ... there is no function I can see with this. So, I would leave it out.
?>
<div class="login-page">
//For the action - use "#" if you want the action is happen on the same page.
<div class="form" method="post" action="#">
<form class="login-form">
<input type="text" name="ldc_username" placeholder="username" value=""/>
<input type="password" name="ldc_password" placeholder="password" value=""/>
<button type="submit" name="submit">login</button>
</form>
</div>
</div>
备注:
https://developer.wordpress.org/reference/functions/wp_send_json/
https://developer.wordpress.org/reference/functions/sanitize_text_field/