0

I'm using $wpdb->insert to insert data into a custom table on my wordpress database.

Unfortunately, it is inserting the data multiple times.

I have searched through other topics posted, and haven't found an answer. I've found some band-ids (making unique keys on the database) which I've done, but that doesn't solve the problem.

From the manual page (https://developer.wordpress.org/reference/classes/wpdb/insert/) the function is to insert a ROW into a table. However, it is doing it at least twice.

After I created the unique key on the table, I was using this code:

$result = $wpdb->insert('training', $data);

if ($result==1) { // do something here }

A row containig the data was inserted, but the code in the IF never happened. To troubleshoot, I put in a var_dump($result), and ran again.

This time, it STILL inserted a row into the database, but the VAR_DUMP indicated bool(false).

This seems to clearly indicate that it is trying it more than once. The first time, it exceeds, and the data is entered, but then for some reason, it's doing it AGAIN, and because of the unique key, it is failing (which is expected because of the unique key).

However, why is it trying twice? This makes me not be able to use an "if success", and I haven't seen any reason why this shouldn't be working.

$wpdb->print_error(); isn't writing anything either.

Attachment uploads (when present) are working as expected.

Full Code on request:

<?php
global $wpdb;

echo "<h2>Add New Events to Schedule</h2>\r\n<form method='post' name='addEvents' enctype='multipart/form-data'>\r\n";
echo "Type of Event <select name='trainingType'>\r\n <p /><option value='open'>Open Training</option>\r\n";
echo "<option value='ONSITE'>Onsite Traning</option>\r\n<option value='AUW'>Advanced User Workshop</option>\r\n";
echo "<option value='ONLINE'>Online Training</option>\r\n";
echo "<option value='EUG'>EQuIS User Group</option>\r\n";
echo "<option value='PAF'>Product Advisory Forum</option>\r\n";
echo "<option value='ACADEMY'>EQuIS Academy</option>"; 
echo "<option value='OH'>Office Hours</option>";
echo "</select>\r\n\r\n<br />";

echo "On Demand?"; 
echo "<input type='checkbox' name='onDemand' value='yes' onChange='odClick();'>";

echo "<br />";

echo "Start Date: (time in ET, for Academy or Office Hours, leave 00:00 for all others)<br />";
   dateDropdowns('start'); 
echo "\r\nEnd Date: (time in ET, for Academy or Office Hours, leave 00:00 for all others)<br />";
 dateDropdowns('end'); 
echo "<p />Location:  <br /> <input type='text' name='location' size='60' maxlength='80' />\r\n\r\n";
echo "<p />Company: <input type='text' name='company' size='60' maxlength='75' />\r\n<br />\r\n";
echo "<p />Cost: $<input type='text' name='cost' size='10' maxlength='10' />\r\n<br />";
echo "<p />Product Name for ACADEMY<br /><input type='text' name='course_num' size='60' />\r\n";
echo "<p />Course Name (ACADEMY - further details on course name)<input type='text' name='course_name' size='60' />\r\n";
echo "<p />Difficulty (ACADEMY, OH): <select name='difficulty'><option value=''>. . . </option><option value='Entry'>Entry</option><option value='Intermediate'>Intermediate</option><option value='Advanced'>Advanced</option>";
echo "</select>"; 
echo "<p />Course Desc (ACADEMY, OH): <br /><textarea name='course_desc'></textarea> "; 
echo "<p />Course Duration: <br /><input type='text' name='duration' size='10' maxlength='14' />\r\n";
echo "<p />URL (registration url for AUW, etc.,): <input type='text' name='url' size='70' />\r\n<br/>\r\n";

 echo "<p />Attachments (pdf flyer, etc):<br /> <input type='file' name='attachment_upload' id='attachment_upload' multiple='false' accept='image/*,.pdf' />"; 

 //nonce just essetially protects against cross site forgery
    wp_nonce_field( 'add_training_event', 'add_training_nonce'); 


echo "<p /><hr /><input type='Submit' name='addTraining' value='Add Event' />\r\n</form>"; 

$months = array(
    1 => "January", 
    2 => "February", 
    3 => "March", 
    4 => "April", 
    5 => "May", 
    6 => "June", 
    7 => "July", 
    8 => "August", 
    9 => "September", 
    10 => "October", 
    11 => "November", 
    12 => "December"
  );  



// if adding a new session - post submit button name 
if(isset($_POST['trainingType']) && wp_verify_nonce($_POST['add_training_nonce'], 'add_training_event'))

    { 

    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
    require_once( ABSPATH . 'wp-admin/includes/media.php' );


 // only try an upload if there is a file attached
if($_FILES['attachment_upload']['size'] > 0) {
    // echo "Attachment Present";
    // var_dump($_FILES);
$file = media_handle_upload($_FILES['attachment_upload'], 0 );

    if ( isset( $file['error'] ) ) {
        echo "Error uploading file: " . $file['error'];

    }
    else {
$attachment_url = $file['url'];
$filename = $file['name'];

echo "Uploaded " . $filename . " - " . $attachment_url;
    } // no errors

} // uploaded attachment if present.
else { // no attachment, but  create a value for the file URL so the post doesn't fail

   $attachment_url = '';
} 


$date = ""; 

$syear = $_POST['startYear'];  
$smonth = $_POST['startMonth']; $tmonth = $months[$smonth]; 
$emonth = $_POST['endMonth']; 
$temonth = $months[$emonth];
 if (strlen($smonth) == 1) { $smonth = "0" . $smonth; } //make 2 day month
$sday = $_POST['startDay']; if (strlen($sday) == 1) { $sday = "0" . $sday; } // make 2 day day
if (strlen($emonth) == 1) { $emonth = "0" . $emonth; } // 2 digit month
$eday = $_POST['endDay']; if (strlen($eday) == 1) { $eday = "0" . $eday; } // 2 digit day

$onDemand = $_POST['onDemand']; if ($onDemand == 'yes') { $onDemand = 1; } else { $onDemand = 0; }

//sql date times
$startdate = $syear . "-" . $smonth . "-" . $sday . " " . $_POST['startHour'] . ":" . $_POST['startMinute'] . ":00";
$enddate = $_POST['endYear'] . "-" . $emonth . "-" . $eday . " " . $_POST['endHour'] . ":" . $_POST['endMinute'] . ":00"; 

if ($_POST['type'] == 'ACADEMY') {
   $date = $tmonth . " " . $sday . ", " . $syear . "  "; 
     if ($_POST['startHour'] > 12) { $date .= $_POST['startHour'] - 12 . ":" . $startMinute . "PM ET"; }
         else if ($_POST['startHour'] == 12) { $date .= $_POST['startHour'] . ":" . $startMinute . "PM ET"; }
        else { $date .= $_POST['startHour'] . ":" . $startMinute . "AM ET"; }
   }

else if ($smonth == $emonth) {
   if ($sday == $eday)  { $date = $tmonth . " " . $sday . ", " . $syear; }
      else { $date = $tmonth . " " . $sday . " - " . $eday . ", " . $syear; }
  } // if months are equal

else {
  $date = $tmonth . " " . $sday . " - " . $temonth . " " . $eday . ", " . $syear; 
 }// months not equal 

$location = $_POST['location']; 
$company = $_POST['company'];
$type = $_POST['trainingType'];
$url = $_POST['url'];

$data = array(
            'date'=> $date,
            'enddate' => $enddate, 
        'company' => $company, 
        'type' => $type, 
        'location' => $location,
        'startdate' => $startdate,
            'url' => $url, 
            'attachment' => $attachment_url,
            'course_num' => $_POST['course_num'], 
            'course_name' => $_POST['course_name'], 
            'course_desc' => $_POST['course_desc'], 
            'cost' => $_POST['cost'], 
            'duration' => $_POST['duration'],
            'difficulty' => $_POST['difficulty'],
            'onDemand' => $onDemand
           );

   //  print_r($data); 

$wpdb->insert('training', $data);

if ($result==1) {
echo "Event Added, click <a href='https://earthsoft.com/support/training/'>here (trainings) </a> or <a href='https://earthsoft.com/newsroom/earthsoft-user-groups/'> here (EUG)</a> to view";
}

else { $wpdb->print_error(); }

}  // end if submit


?>
  • Most likely your code is running twice. Can you paste a reproducable snippet into the question? – kero Oct 24 '19 at 16:21
  • Thanks, sorry, this is my first time – Rian Weaver Oct 24 '19 at 16:25
  • 1
    No problem :) Now how are you calling this? Side note: when talking code it usually helps us a lot to help you, if you can provide a minimum reproducible example – kero Oct 24 '19 at 16:27
  • 1
    @RianWeaver where does your code snippet go? Is that an mu-plugin? functions.php? Page template? How should it be ran? Is it called directly in the browser? Or is it loaded by WP? – Tom J Nowell Oct 24 '19 at 16:40
  • 1
    That's mildly horrifying, you should avoid plugins that let you save PHP code inside the database as it's a major security risk, encourages bad habits, and provides a dead end for WP development with lots of problems and restrictions. As well as that a lot of what people will advise and what you read simply doesn't apply to your situation. Even the fundamental assumption that the PHP code is in a file is incorrect in this case. As a result, I don't believe it's possible to diagnose why it inserts twice while you're using this plugin – Tom J Nowell Oct 24 '19 at 17:12

Your Answer

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

Browse other questions tagged or ask your own question.