hi i have decided to store few values in a separate table, So i created it and now i used a form to store values but when i process that form i’m getting error Trying to get property of non-object
and Call to a member function insert() on a non-object
Even though i declared global $wpdb;
Here is the form
<form action="formaction.php" method="post">
<input type="text" name="name1" value="">
<input type="text" name="name2" value="">
<input type="submit" name="submit" value="add">
</form>
formaction.php
if(isset($_POST['name1']))
{
$db_data1=$_POST['name1'];
}
if(isset($_POST['name2']))
{
$db_data2=$_POST['name2'];
}
function res()
{
global $wpdb,$db_data1,$db_data2;
$my_table_name=$wpdb->prefix."my_table";
$name1=$db_data1;
$name2=$db_data2;
$rows_affected = $wpdb->insert( $my_table_name, array( 'first' => $name1, 'last' => $name2 ) );
}
res();
according to error $wpdb is not an object but i have used global, what is the bug in this code? am i doing correctly ?
You’re posting directly to
formaction.php
, as such WordPress is never loaded and so you do not have access to any of its API, including the database API stored inglobal $wpdb
(which is causing the error). I’d recommend keeping everything in WordPress… and a useful method for form handling is usingadmin-post.php
(if you’re familiar with WordPress’ ajax handling – this is a similar idea).The idea is that you post to the url
which you can get via
admin_url('admin-post.php');
. And you post – along with any data and nonces – a unique value for theaction
variable. (Let’s saywpse111797_form_submitted
). When the form is submitted toadmin-post.php
, WordPress will trigger the hook:admin_post_wpse111797_form_submitted
– if you are logged inadmin_post_nopriv_wpse111797_form_submitted
– if you are logged outSo your form might look like:
Please don’t forget to uses nonces to verify intent.
You can then hook onto either of the above hooks (or both) depending on whether you want to handle form submissions from logged in users, guests, or both.