我如何添加一条消息“$ user_id Deleted”或“$ user_id not found?”

时间:2011-01-02 05:00:19

标签: php mysql

我如何添加一条消息“$ user_id已删除”或“$ user_id not found?”

  <?php

  $con=mysql_connect("localhost","root","");

  if(!$con) {
      die('could not connect:'.mysql_error());
  }

  mysql_select_db("final?orgdocs", $con);

  $user_id = $_POST["user_id"];

  $result = mysql_query("delete from account where user_id='$user_id' ");


  ?>

5 个答案:

答案 0 :(得分:1)

$user_id = $_POST["user_id"];

if(isset($user_id)) {
    $result = mysql_query("delete from account where user_id='$user_id' ");

    $affected_rows = mysql_affected_rows();    // how many rows deleted?

} else {
    $user_id = "";
    $result = false;
    $affected_rows = 0;
}

if($result == true && $affected_rows > 0) {
    echo "User " . $user_id . " deleted."; 
} else {
    echo "User " . $user_id . " not found.";
}

这应该有助于您入门。您可以将响应返回到您的调用页面,然后使用JQuery之类的JavaScript库在HTML中显示它。

编辑:我编辑了代码以获取受影响的行,因为删除查询可以返回true但删除0条记录。

http://www.php.net/manual/en/function.mysql-affected-rows.php

答案 1 :(得分:1)

<?php

$con = mysql_connect("localhost", "root", "");

if (!$con) {
    die('could not connect:'  .mysql_error());
}

mysql_select_db("final?orgdocs", $con);

$user_id = (int)$_POST["user_id"];

$result = mysql_query("delete from account where user_id=$user_id");

$affected_rows = mysql_affected_rows();

if ($affected_rows) {
    echo "User ID '$user_id' deleted";
} else {
    echo "User ID '$user_id' not found";
}

?>

答案 2 :(得分:0)

echo $ user_id +'已删除或未找到';

答案 3 :(得分:0)

只需将其添加到最后:

return "user id " . ( $deleted ? "deleted" : "not found");

答案 4 :(得分:0)

来自mysql_query手册页:

  

对于SELECT,SHOW,DESCRIBE,EXPLAIN和其他返回结果集的语句,mysql_query()会在成功时返回资源,或者在出错时返回FALSE。

     

对于其他类型的SQL语句,INSERT,UPDATE,DELETE,DROP等,mysql_query()成功时返回TRUE,错误时返回FALSE。

所以,它应该继续这样:

if ($result === TRUE) {
    echo "Account deleted.";
} else if ($result === FALSE) {
    echo "Account not found.";
}