Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

php - Why last row deleted when refresh page in wordpress

When I refresh page table row deleted and last query deleted when I click on any delete button of other row. Why is this happened? This is table which I displayed

<?php
global $wpdb;
$table= 'wp_contact_form';
$result = $wpdb->get_results ( "SELECT * FROM $table" );

if(!empty($result)){

foreach ( $result as $print ) {  
        
?>
<tr>
<td><?php echo $print->id;?></td>
<td><?php echo $print->names;?></td>
<td><?php echo $print->emails;?></td>
<td><?php echo $print->gender;?></td>
<td><?php echo $print->age;?></td>
<td><input type="submit" value="Edit" id="" name="update"></td>
<td><input type="submit" value="delete" id="delete" name="delete"></td>
</tr>
<?php
}
} 
?>

this is delete query

$id= $print->id;
if(isset($_POST['delete']))
{
    $result = $wpdb->delete($table, array('id' => $id));
    if(!empty($result))
    {
        echo "success";
    }
}

error screenshot - https://prnt.sc/wdg3xv


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're not specifying which ID should be deleted if $_POST['delete'] is set, right now you're asking WP to just delete something.

You need to wrap your elements in a form and add a field that contains the exact ID of the element you want to delete, like this:

<td>
  <input type="submit" name="delete" value="delete" />
  <input type="hidden" name="targetItem" value="<?php echo $print->id;?>" />
</td>

Then in your PHP use that field's ID to delete it from the DB:

if (isset($_POST['delete']))
    $result = $wpdb->delete($table, array('id' => $_POST['targetItem']));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...