Make more than one database call in wordpress plugin
-
I have 2 pieces of code from a simple plugin that work independently from each other but don’t work together.
if(isset($_POST['submit'])){ if(has_presence($_POST['product_name'])){ insert_row_into_table('CAL_products'); show_errors(); if(has_presence($wpdb->last_query)) { echo "Update Successful"; } else { echo "Update Failed"; } } else { echo "The field 'Product Name' cannot be blank."; } }
And this one
$results_array = $wpdb->get_results("SELECT * FROM wpCMS_CAL_products ORDER BY id ASC"); echo build_table_from_results_array($results_array);
The functions are included at the bottom.
The problem I have is that when the page loads there is no $_POST so it skips over the if statement and builds the table. This table builds fine.
When the form is submitted the if statements come back true and the new value is added to the database successfully, but then the table doesn’t build until the page is refreshed. If the code to build the table is put at the top above the if statement it builds fine but doesn’t include the new value until the page is refreshed.
Is it possible to add a new item to the database table before the results are populated to the HTML table?
function insert_row_into_table($table_name){ global $wpdb; $prefix = $wpdb->prefix; //Define the wordpress table prefix $table = $prefix . $table_name; //Build the table name unset($_POST['submit']); echo print_r($_POST); $data = $_POST; //collect the data from post $wpdb->insert( $table, $data ); //insert data into the table } function show_errors(){ echo $wpdb->show_errors(); echo $wpdb->print_error(); } function has_presence($value) { return isset($value) && $value !== ""; } function build_table_from_results_array($results_array) { $out = ""; $out .= "<table class=\"widefat\">"; $out .= "<thead>"; foreach($results_array[0] as $key => $element) { if($key == "id") { $out .= "<th class=\"id-column\">"; $out .= strtoupper($key); $out .= "</th>"; } else { $out .= "<th>"; $out .= ucwords(str_replace("_", " ", $key)); $out .= "</th>"; } } $out .= "</thead>"; $out .= "<tbody>"; $i = 0; foreach($results_array as $key => $element){ if($i % 2 === 0) $extraclass= "alternate"; $out .= "<tr class=\"$extraclass\">"; $i++; $extraclass=""; foreach($element as $subkey => $subelement){ $out .= "<td>$subelement</td>"; } $out .= "<td><a href=\"#\">EDIT</a></td>"; $out .= "</tr>"; } $out .= "</tbody>"; $out .= "</table>"; return $out; }
- The topic ‘Make more than one database call in wordpress plugin’ is closed to new replies.