Flo
Flo

Reputation: 33

WordPress and PHP | Check if row exists in database if yes don't insert data

I'm fairly new to WordPress and SQL. I have a contact form that I want to have the data be submitted to my WordPress database but only if the data that has been entered has not been entered before.

This is what i have so far, which sends data to my database when form is submitted.

if(isset($_POST['contact_us'])) {
    $invalidContact = "<h5 class='invalidBooking'> Nope try again</h5>";
    $successContact = "<h5 class='invalidBooking'> Message Sent!</h5>";
    $table_name='contact_table';
    global $wpdb;

    $contact_name = esc_attr($_POST['contact_name']);
    $contact_email = sanitize_email($_POST['contact_email']);
    $subject = esc_attr($_POST['subject']);
    $message = esc_attr($_POST['message']);

    $error= array();


    if (empty($contact_name)) {
        $error['name_invalid']= "Name required";
    }
    if (empty($contact_email)){
        $error['email_invaild']= "Email required";
    }

    // Im guessing some code here to check if row exists in database

    if (count($error) >= 1) {
        echo $invalid;
    }
    if (count($error) == 0) {
        $data_array=array(
            'Contact_Name'=>$contact_name,
            'Contact_Email'=> $contact_email,
            'Contact_Subject'=> $subject,
            'Contact_Message'=> $message,
        );

        $rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
        echo $successContact;
    } 

}

Upvotes: 3

Views: 6505

Answers (2)

Krishna Joshi
Krishna Joshi

Reputation: 315

You may try this code

if (count($error) == 0) {
    $data_array=array(
        'Contact_Name'=>$contact_name,
        'Contact_Email'=> $contact_email,
        'Contact_Subject'=> $subject,
        'Contact_Message'=> $message,
    );

 $query = "SELECT * FROM $table_name WHERE 'Contact_Name'= '$contact_name' AND 'Contact_Email' = '$contact_email' AND 'Contact_Subject' = '$subject' AND 'Contact_Message' = '$message'";
 $query_results = $wpdb->get_results($query);
 if(count($query_results) == 0) {
    $rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
 }
}

Hope this works for you.

Upvotes: 2

Parth Shah
Parth Shah

Reputation: 411

fetch data using this code

$query = "SELECT * FROM {$wpdb->prefix}table WHERE column = 1";
echo $query;
$results = $wpdb->get_results($query);

and then you know what to do...

Upvotes: 0

Related Questions