Thursday 19 January 2012

How to write sql query and form in wordpress plugin at admin end

When writing plugins, it's a good idea to keep your data-handling within the plugin's main file (i.e. not sending it to a separate file), and activate functions to handle it accordingly. Basically, you can set your form's action to point to either the plugin's file, or the page that contains the form. else following error will occur.

Fatal error: Call to a member function get_results() on a non-object (jQuery From Plugin & WordPress)
the main plugin file which appear as plugin page , always write sql quries there you need put some flag $_POST['flag'] to distingush quries coming from which section.

<form id="frmfbdata" name="frmfbdata" method="POST" action="<?php echo str_replace( '%7E', '~', $_SERVER['REQUEST_URI']); ?>">
 <input type="text" id="username"  name="username" value="">
 <input type="text" id="useremail" name="useremail" value="">
 <input type="text" name="fconnect" id="fconnect" value="y">
 </form>
 
global $wp_table,$wpdb;
$email=$_POST['email'];
$name=$_POST['name'];
if($email!=""){
 $querystr = "SELECT count(*)as cnt FROM $wpdb->options WHERE $wpdb->options.option_name = 'addbanner'";
 $result = $wpdb->get_results($querystr);
 //**Array ( [0] => stdClass Object ( [cnt] => 0 ) )

$recordcount=$result[0]->cnt;
 if($recordcount==0){
  $mydata=array();
  $mydata['email']=$email;
  $mydata['name']=$name;
  $data=json_encode($mydata);
  $query = "INSERT INTO $wpdb->options SET blog_id='0',option_name='addbanner',option_value='".$data."',autoload='no'";
  $wpdb->get_results($query);
 }
}


ajax query to a page works but if sql query is written it shows fatal error
 
function
var name=document.getElementById("username").value;
var email=document.getElementById("useremail").value;
document.getElementById('frmfbdata').submit();
var ajaxurl = "<?php bloginfo('wpurl') ?>/wp-content/plugins/addbanner/myajax.php";
var data = {
email: email,
name: name
};


//** since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php

jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});

}callajax(){

No comments:

Post a Comment