0

I have a plugin that reads data from WordPress database. I want the admin to be able to delete a record from the database using the data's ID. how do i do this... i have tried

 if ($_GET) {
    if ( isset( $_GET['in_delete'] ) ) {
        global $wpdb;
        $result = $wpdb->get_results( "SELECT * FROM bookings" );

        foreach ( $result as $print ) {
            $id = $print->id;
            $del =  $wpdb->delete( 'bookings', $id );
            if ( $del ) {
                echo "<script>
                        alert('record deleted');
                      </script>";
            }
        }
    }
}

and my button is

<form action="" name="operations" method="get" >
    <input type="button" name="in_delete" value="Delete" style="color:#fff; height:19px; width: 60px; font-size:10px; background-color: red;cursor: pointer;"><br>
</form>
1

OK, so your code can't work, because you use $wpdb->delete incorrectly.

Let's take a look at Codex. $wpdb->delete takes 3 params (one is optional):

  • $table (string) (required) Table name. Default: None
  • $where (array) (required) A named array of WHERE clauses (in column -> value pairs). Multiple clauses will be joined with ANDs. Both $where columns and $where values should be 'raw'. Default: None
  • $where_format(string/array) (optional) An array of formats to be mapped to each of the values in $where. If a string, that format will be used for all of the items in $where. A format is one of '%d', '%f', '%s' (integer, float, string; see below for more information). If omitted, all values in $where will be treated as strings unless otherwise specified in wpdb::$field_types. Default: null

And it returns:

It returns the number of rows updated, or false on error.

So what's wrong with your code?

$id = $print->id;
$del =  $wpdb->delete( 'bookings', $id );

You pass $id as second param, but it's just a number, and you should pass an array of where clauses...

So how should it look?

foreach ( $result as $print ) {
    $del =  $wpdb->delete( 'bookings', array( 'id' => $print->id ) );
    if ( $del ) {
        echo "<script>
                  alert('record deleted');
              </script>";
    }
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.