0

I have a php script that listens for $_POST input, and inserts into my table which can then be read in my Wordpress plugin and displayed to the admin. Given how people submit forms multiple times, I check the database to see if the entry already exists, using a unique invoice number that is sent in the form.

My code is:

global $wpdb; 
$submits_table = $wpdb->prefix . 'submits_table';
$invoice = $_POST['invoice'];
$exists = $wpdb->get_row( "SELECT * FROM $submits_table WHERE `invoice` = $invoice" );
    if ( $exists == NULL ) {

        $wpdb->insert(
            $submits_table,
                array(
                'first_name' => $_POST['first_name'],
                'ip_address' => $_POST['ipaddress'],
                'invoice' => $invoice
            ),
            array(
                '%s',
                '%s',
                '%s'
            )
        );

}

The problem is that every single submission gets inserted, regardless whether the invoice number already exists or not. I've tried this same code on a different page from the Admin panel and it works okay; it's only when it's set as a listener for the front end submissions does it not work right.

I'm ripping my hair out. Any ideas as to why get_row() is returning NULL every time on the front end but not the admin?

EDIT: invoice is alphanumeric, so it's varchar.

  • is invoice column VARCHAR or INT – Tamil Selvan C Mar 13 '17 at 12:36
  • 2
    Restricting inserts based on uniqueness (whether it exists) is done by placing `unique` constraint on the database level, you don't do this from PHP. Reason why you don't do it from PHP Is exactly what you're experiencing - PHP can't enforce uniqueness, or any other language for that matter. Only database can do it. – Mjh Mar 13 '17 at 12:39

1 Answers1

0

wpdb::get_row

Return

(array|object|null|void) Database query result in format specified by $output or null on failure

so , it will not be a proper way to check for existents with null

instead, check the count of the returned result:

if (count($exists) > 0)
hassan
  • 7,812
  • 2
  • 25
  • 36