Home >Backend Development >PHP Tutorial >Why can't this delete the selected data?
What’s wrong?
<code><!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> </style> </head> <body> <form method="post"> <?php header('content-type:text/html;charset=utf-8;'); $pdo=new PDO("mysql:host=localhost;dbname=t1","root",""); $stmt=$pdo->prepare("select name from class"); $stmt->execute(); $res=$stmt->fetchall(PDO::FETCH_ASSOC); foreach($res as $v){ echo '<span>'.$v['name'].'<input id="ipt3" type="checkbox" name="name">'.'</span>'; } ?> <button type="submit">删除</button> </form> <?php if(isset($_POST['name'])){ header('content-type:text/html;charset=utf-8;'); $pdo=new PDO("mysql:host=localhost;dbname=t1","root",""); $stmt2=$pdo->prepare("delete from class where name=?"); $stmt2->execute(array($_POST['name'])); } ?> </body> </html> </code>
What’s wrong?
<code><!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> </style> </head> <body> <form method="post"> <?php header('content-type:text/html;charset=utf-8;'); $pdo=new PDO("mysql:host=localhost;dbname=t1","root",""); $stmt=$pdo->prepare("select name from class"); $stmt->execute(); $res=$stmt->fetchall(PDO::FETCH_ASSOC); foreach($res as $v){ echo '<span>'.$v['name'].'<input id="ipt3" type="checkbox" name="name">'.'</span>'; } ?> <button type="submit">删除</button> </form> <?php if(isset($_POST['name'])){ header('content-type:text/html;charset=utf-8;'); $pdo=new PDO("mysql:host=localhost;dbname=t1","root",""); $stmt2=$pdo->prepare("delete from class where name=?"); $stmt2->execute(array($_POST['name'])); } ?> </body> </html> </code>
Your code is rather strange.
First let’s talk about why it cannot be deleted:
Your input box does not have a value attribute. So your $_POST['name'] cannot get the value.
You can change it to
<code>echo '<span>'.$v['name'].'<input type="checkbox" name="name" value="'.$v['name'].'"></span>'; </code>
Then I look at your code. Do you want to delete multiple selections? Then you need to post an array to PHP, then you can modify the name attribute of the input:
<code>echo '<span>'.$v['name'].'<input type="checkbox" name="name[]" value="'.$v['name'].'"></span>'; </code>
Then the post received using php is like this:
<code>$name = $_POST['name'];//array(name1,name2....) </code>
At this time you need to deal with this $name. Change your sql statement to
<code>delete from class where name in (name1,name2,name3...) </code>
For example:
<code>$sql = "delete from class where name in (" . trim(str_repeat('?,',count($name)),',') . ")"; $stmt2 = $pdo->prepare($sql); $stmt2->execute($name); </code>
Then, your code for judging is_post is best before outputting the list. Otherwise, you will be output first and then deleted, and you will not see the effect.
Are you just getting started?