query - Deleting data from a custom table in WordPress

admin2025-06-05  2

I am trying to delete records from my custom table but it does not delete anything.

Here is my code:

<?php
global $wpdb;
$retrieve_data = $wpdb->get_results( "SELECT * FROM wp_paypal" );

// some code to display here...

?>
<form method="post" enctype="multipart/form-data">
   <td><input type="submit"  name="delete" value="Delete"  /></td>
</form>
<?php
$myid= $retrieved_data->id;

if (isset($_POST['delete'])) {
        //global $wpdb;
        $wpdb->query(
              'DELETE  FROM $wpdb->paypal
               WHERE id = "'.$myid.'"
              '
        );

    }
}

I am trying to delete records from my custom table but it does not delete anything.

Here is my code:

<?php
global $wpdb;
$retrieve_data = $wpdb->get_results( "SELECT * FROM wp_paypal" );

// some code to display here...

?>
<form method="post" enctype="multipart/form-data">
   <td><input type="submit"  name="delete" value="Delete"  /></td>
</form>
<?php
$myid= $retrieved_data->id;

if (isset($_POST['delete'])) {
        //global $wpdb;
        $wpdb->query(
              'DELETE  FROM $wpdb->paypal
               WHERE id = "'.$myid.'"
              '
        );

    }
}
Share Improve this question edited Nov 30, 2018 at 13:52 Maxime 1337 bronze badges asked Jun 20, 2015 at 7:11 user3463054user3463054 311 gold badge1 silver badge3 bronze badges 1
  • What problem are you facing? – sakibmoon Commented Jun 20, 2015 at 7:51
Add a comment  | 

2 Answers 2

Reset to default 6

Try to use $wpdb->prefix insted of $wpdb in Delete query.

Example:

 $wpdb->query(
              'DELETE  FROM '.$wpdb->prefix.'paypal
               WHERE id = "'.$myid.'"'
);

I know I'm late... but the main issue in your question is that you are using single quotes (') in your statement:

$wpdb->query(
      'DELETE  FROM $wpdb->paypal
       WHERE id = "'.$myid.'"
      '
);

This means that $wpdb->paypal is not producing the result you are expecting. First, you assume this displays the "paypal" table name. But it doesn't.

If $myid has a value of 4, your PHP code will produce this SQL statement :

DELETE FROM $wpdb->paypal WHERE id = 4

... instead of being:

DELETE FROM wp_paypal WHERE id = 4

To fix the issue, you must:

  1. Change your single quotes to double quotes. (Read why)
  2. Add the table prefix in front of the table name.

Like this:

$table_name = $wpdb->prefix . 'paypal';
$wpdb->query( "DELETE  FROM {$table_name} WHERE id = '{$myid}'" );

Also, make sure you sanitize the $myid variable because if I submit the value 0 OR 1=1, this will produce this SQL statement:

DELETE FROM wp_paypal WHERE id = 0 OR 1=1

... and will delete every row in the table

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749138338a316685.html

最新回复(0)