1

I created this simple function to update a row inside a table called wp_todos

function update_completed_todos($id,$complete) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'todos';
    $result = $wpdb->get_results("SELECT id FROM " . $table_name .  " WHERE id = '" .$id."'");
    if (count ($result) > 0) {
        $wpdb->update( 
            $table_name, 
            array(  
                'complete'   =>  $complete, 
            ),
            array( 'id' => $id )
        );
    }
}

It simply passes 2 variables: $id and $complete.

Then I created a foreach loop:

$todos = $wpdb->get_results("SELECT * FROM " . $table_name);
foreach ($todos  as $key => $value) {
     <input id="<?php echo $value->id; ?>" type="submit" onclick="<?php update_completed_todos($value->id, 1); ?>" value="<?php esc_attr_e( 'Done' ); ?>" />
}

As you see it should submit "1" to a specific column complete in a specific row. The issue here is when I click on the button it affects all the rows inside the table instead of the target one row. In other word it makes the entire column complete taking the value of "1".

codewitharefin
  • 1,398
  • 15
  • 24
Yamona
  • 1,070
  • 1
  • 16
  • 36
  • I think you'll find it's updating _before_ you click the button - the updates are being performed as the page renders. `onclick` can't call PHP like that. You'll need the javascript to call a function on the server, probably with AJAX. See the answers on [this question](http://stackoverflow.com/a/19323136), though that's not WordPress specific – Hobo Jul 28 '16 at 03:37
  • Also, check out [the section of the codex on SQL injection](https://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks). If your ID is coming from the browser, just concatenating it into a string (in your SELECT) is dangerous - read up on and use `$wpdb->prepare()` – Hobo Jul 28 '16 at 03:40
  • OK, thanks @Hobo I will check the two references you sent. Also ID does not coming from the browser, it came from the database as you can see I used `$todos = $wpdb->get_results` to query the database. – Yamona Jul 28 '16 at 04:06
  • Sorry, I meant it _will_ come from the browser (or at least, I assume it will) - you'll have to send it from the browser when you click the button. And if it is coming from the browser, a malicious user could change it to something unexpected. Best to get in the habit of using `$wpdb->prepare()` just in case – Hobo Jul 28 '16 at 04:13
  • 1
    [Here](http://wordpress.stackexchange.com/a/227403/264) is an example of doing something similar in WordPress, using the [AJAX API](https://codex.wordpress.org/AJAX_in_Plugins). You should be able to add the PHP code to your theme's functions.php – Hobo Jul 28 '16 at 04:21
  • @Hobo your last comment somewhat help, thank you. – Yamona Jul 28 '16 at 06:20

0 Answers0