如果没有删除DB行,则返回false?

时间:2012-11-30 12:18:21

标签: php mysql

我对PHP有点新手,但我现在正在做一个基于它的课程。

我有一个表单,用户将输入他们的电子邮件地址,以便从电子邮件列表中删除它。

我正在尝试制作一个if else声明,当他们的电子邮件不在数据库中时,它会出错,并且“列表中不存在”。

您可能会看到脚本不起作用。

如何查看查询是否成功,然后向用户返回相应的消息?

    $email = $_POST['email'];

    $dbc = mysqli_connect(censored)
            or die('error connecting to the database');
    $query = "DELETE FROM email_list WHERE email='$email'";
    $result = mysqli_query($dbc, $query)
            or die('Error Querying the database');

    if ($result == 0) {

        echo $email . ' do not exist in the list';
    }
    else {
        echo $email . ' is deleted form the list';
    }

    mysqli_close($dbc);

2 个答案:

答案 0 :(得分:3)

mysqli_affected_rows()

<?php
$email = $_POST['email'];

$dbc = mysqli_connect(censored)
        or die('error connecting to the database');
$query = "DELETE FROM email_list WHERE email='$email'";
$result = mysqli_query($dbc, $query)
        or die('Error Querying the database');

if (mysqli_affected_rows($dbc) === 0) {

    echo $email . ' do not exist in the list';
}
else {
    echo $email . ' is deleted form the list';
}

mysqli_close($dbc);
?>

答案 1 :(得分:0)

HTML代码

<html>
<form method="post" action="somepage">
<input type="text" name="email" />
<br/>
<input type="Submit" name="submit" value="Delete" />
</form>
</html>

Php Code

<?php
// on submit button 
if (isset($_POST["submit"]))
{
$dbhost = 'localhost';
$dbuser = 'databaseuser';
$dbpass = 'databasepassword';
$dbname = 'databasename';
//connection to mysql
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn)
{
die('Could not connect: ' . mysql_error());
}
//use database
$usedb = mysql_select_db($dbname , $conn);
if (!$usedb)
{
die ("could not select $dbname...<br/>");
}
//to delete record
$del="DELETE FROM tablename WHERE columnName = '$email'";
if(mysql_query($del))
{
echo '<script type="text/javascript">alert("Record Deleted Successfully....!")</script>';
}
else
{
echo mysql_error();
}
}
?>

希望这对你有所帮助。