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.'"
'
);
}
}
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:
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