哪里不对呢?
<code> <title></title> <style type="text/css"> </style> <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'])); } ?> </code>
哪里不对呢?
<code> <title></title> <style type="text/css"> </style> <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'])); } ?> </code>
你这代码,写的比较奇怪。
先说为什么不能删除:
你的input的框 没有 value 属性。所以你的$_POST['name']拿不到值。
你可以改成
<code>echo '<span>'.$v['name'].'<input type="checkbox" name="name" value="'.$v['name'].'"></span>'; </code>
然后我看你的代码,你是想做多选删除吧?那么你需要post提交一个数组到php,那么你可以修改input的name属性:
<code>echo '<span>'.$v['name'].'<input type="checkbox" name="name[]" value="'.$v['name'].'"></span>'; </code>
然后用php接到的post是这样的:
<code>$name = $_POST['name'];//array(name1,name2....) </code>
这时你需要处理这个$name。更改你的sql语句为
<code>delete from class where name in (name1,name2,name3...) </code>
比如下面:
<code>$sql = "delete from class where name in (" . trim(str_repeat('?,',count($name)),',') . ")"; $stmt2 = $pdo->prepare($sql); $stmt2->execute($name); </code>
然后,你的判断is_post的代码最好在输出列表之前,否则,先给你输出,后删除,看不到效果。
这是刚入门吗?