As for me, I tried to realize a widget with database activities, i.e. to create and drop tables, insert and update records. There is another one from Wordpress Codex which is ultimately helpful.
This post is in no place to substitute any of them listed above. However, when I was trying with my idea, everything works together well except that the code in the control panel method of my widget always gets executed twice! In terms of database, that is redundant data.
If you did follow those posts, your widget's control panel method will look like this:
//Control panel method
function control(){
//essential declaration
global $wpdb;
//set table name again
$table_name = $wpdb->prefix . "mytable";
//test if the form is submit,that is the save button clicked, get the arguments from the form
if ( isset($_POST['mywidget-submit'])){
//some parameter transaction here
//prepare query
$insertsql='INSERT INTO '
.$table_name
.'(a,b,c,d,e)'
.'VALUES'
.'( A,B,C,D,E);';
//execute query and write into database
$wpdb->query( $insertsql );
}
}
//design the control panel form here and output
$control_form=''.'...'
echo $control_form;
}
It is absolutely right and working. If you are just using add,update,delete_option (refer to the Wordpress functions) to manipulate your parameters. This is totally fine. In my case, the INSERT statement will be run twice every time the "Save" button is hit on the widget control panel.
Here is how it works:
When the "Save" button is pressed,the "hidden" input control in our control panel form is submitted and the whole is method is called. Now that we test the value from $_POST if the "hidden" control is submit and run the code to insert the Sql statement.
I suspect that when it is done, the control panel will be reloaded again by Wordpress however the $_POST['mywidget-submit'] status is never changed. That's why it happens twice every time.
My solution to this is simple (I believe this is not a perfect one. Let me know if you have others.) To explicitly unset the &_POST['mywidget-submit'] when the code is run, in this case, just after the Sql statement is issued.
//unset the post array otherwise the query is run twice
unset($_POST['mywidget-submit']);

