0

I cant find any syntax for custom queries, use of $wpdb is new to me so can anyone help me solving this??

if(isset($_POST['submit']))
{
 global $wpdb;

$tablename='wp_form_subscribe';

$myrows = $wpdb->get_results( "SELECT * FROM wp_form_subscribe   where     email=$wpdb->email" );
 if($myrows==0)
 {
 $data=array(
 'name' => $_POST['fullname'], 
 'age' => $_POST['age'],
 'email' => $_POST['email']);


  $wpdb->insert( $tablename, $data);
  }
  else 
  {
  $status='User already subscribed';
  }
  $status='';
  }
0

Assuming that all of your sql column names are correct, something like this should work:

if(isset($_POST['submit'])){
    global $wpdb;
    $tablename= $wpdb . 'form_subscribe';
    $myrows = $wpdb->get_var( $wpdb->prepare("SELECT email FROM $tablename WHERE email=%s LIMIT 1", $_POST['email']));
    if(empty($myrows)){
        $data=array(
            'name' => $_POST['fullname'], 
            'age' => $_POST['age'],
            'email' => $_POST['email']
        );
        $wpdb->insert( $tablename, $data);
    }
    else {
        $status='User already subscribed';
    }
    $status='';
}

I changed $wpdb->email to $_POST['email'], I think that is what you meant there. Additionally, I added the $wpdb->prepare() function for sanitation and $wpdb->prefix for best practices.

Since you are doing a lookup to check for something existing (i.e. 1 existing record means the same thing as 1000 existing records for our purposes) I changed $wpdb->get_results() to $wpdb->get_var() and added a limit clause. This will make the query more efficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.