在PHP中删除数据库中的行

时间:2013-04-10 21:07:08

标签: php database

我想从MySQL数据库中删除一行,但我无法执行此操作,尽管我可以更新该行。 第一部分是更新代码,第二部分是删除代码。

有趣的是它向我展示了成功删除的警报,但实际上在MySQL数据库中没有任何改变。

<?php
// for updating Check if button name "Submit" is active, do this 
if(isset($_POST['Submit']) && $_POST['Submit'] == 'update')
  {
$sql1=mysql_query(" UPDATE `".$tbl_name."` SET  `username`='".$_REQUEST['user']."' , `password`='".$_REQUEST['pass']."' , `name`='".$_REQUEST['name']."' , `lastname`='".$_REQUEST['lastname']."' , `phone`='".$_REQUEST['phone']."' , `state`='".$_REQUEST['state']."' , `details`='".$_REQUEST['details']."'  WHERE `id`='".$_REQUEST['id']."' ");
$result1=mysql_query($sql1);
  }

if(isset($result1)){
?>
<script language="javascript">alert('successfuly updated');</script>
<?php
print(redirect('editteacher.php'));
}
  mysql_close();

?>

<?php
//for deleting Check if button name "Submit" is active, do this 
  if(isset($_POST['delete']) && $_POST['delete'] == 'delete user')
  {
$sql1=" DELETE FROM `".$tbl_name."` WHERE `username`='789' ";

$result1=mysql_query($sql1);

if(isset($result1)){
?>
<script language="javascript">alert('successfuly deleted');</script>
<?php

print(redirect('editteacher.php'));
  }
}
mysql_close();

?>

2 个答案:

答案 0 :(得分:1)

替换此行

$result1=mysql_query($sql1);

通过

$result1=mysql_query($sql1) or die(mysql_error());

这将显示代码中的任何错误。

总的来说,我建议您改进代码:

$html = "";
$redirectTo = "";

// for updating Check if button name "Submit" is active, do this 
if(isset($_POST['Submit']) && $_POST['Submit'] == 'update')
{
  $q = " UPDATE `".$tbl_name."` SET  `username`='".$_REQUEST['user']."' , `password`='".$_REQUEST['pass']."' , `name`='".$_REQUEST['name']."' , `lastname`='".$_REQUEST['lastname']."' , `phone`='".$_REQUEST['phone']."' , `state`='".$_REQUEST['state']."' , `details`='".$_REQUEST['details']."'  WHERE `id`='".$_REQUEST['id']."' ";
  $sql1 = mysql_query($q);
  $result1 = mysql_query($sql1) or die(mysql_error());

  if($result1){
    $html = "<script language=\"javascript\">alert(\"successfuly updated\");</script>";
    $redirectTo = "editteacher.php";
    //not sure what you are trying to do here?
    //print(redirect('editteacher.php'));
  }
}
//for deleting Check if button name "Submit" is active, do this 
elseif(isset($_POST['delete']) && $_POST['delete'] == 'delete user')
{
  $q = " DELETE FROM `".$tbl_name."` WHERE `username`='".$_REQUEST['user']."' ";
  $sql1=mysql_query($q);
  $result1=mysql_query($sql1);

  if($result1){
    $html = "<script language=\"javascript\">alert(\"successfuly deleted\");</script>";
    $redirectTo = "editteacher.php";
    //not sure what you are trying to do here?
    // print(redirect('editteacher.php'));
  }
}

echo $html;
if($redirectTo){
  print(redirect($redirectTo));
}
mysql_close();

答案 1 :(得分:0)

  1. 删除双重查询

    更改$sql1=mysql_query(" UPDATE“。$ tbl_name。” to $ sql1 =“UPDATE`”。$ tbl_name。“因为您有双重查询。