nu everest nu everest - 10 days ago 6
MySQL Question

PHP old data still showing after POST

The code below works, in that, it updates the database correctly. However, after the post is completed the data on the page is old i.e.

$reader_busy[0]
is not updated even though it is driven by a SELECT query.

To force
$reader_busy[0]
to update properly on the users screen a refresh is required. This means the pages reloads after the post and then refreshes.

How do I get the page to display the correct data from the mysql without having to load the page twice?

Simplified version of my PHP code:

<?php
$reader_key = 'jm2';
$reader_busy_query = "SELECT `BusyWithClient` " .
"FROM {$wpdb->prefix}assistant " .
"WHERE `Key`='" . $reader_key . "'";

$reader_busy = $wpdb->get_col( $wpdb->prepare( $reader_busy_query ) );
$busy_with_client = $reader_busy[0];

if(isset($_POST['toggle'])){
$result = $wpdb->update(
$wpdb->prefix . 'assistant',
array('BusyWithClient' => $busy_with_client),
array('Key' => $reader_key)
);

// I want to remove / replace this line, and still see updated data.
echo "<meta http-equiv='refresh' content='0; url=" . curPageURL() . "#instructions" . "'>";
}
?>

<h1>
<?php print_r('busy: ' . $reader_busy[0]); ?>
<h1>

<form method="post" action="<?php echo curPageURL() . '#instructions'; ?>">
<input type="submit" name="toggle" value="toggle" >
</form>

Answer

Just flip the order of how you do things. Instead retrieving then updating, update before you retrieve.

<?php 
if (isset($_POST['toggle'])) {
    $result = $wpdb->update(
        $wpdb->prefix . 'assistant',
        array('BusyWithClient' => $busy_with_client), 
        array('Key' => $reader_key)                
    );   
}

$reader_busy_query = "SELECT `BusyWithClient` " .
                     "FROM {$wpdb->prefix}assistant " .
                     "WHERE `Key`='" . $reader_key . "'";

$reader_busy = $wpdb->get_col($wpdb->prepare($reader_busy_query));
?>