How to make sure delete query removes a row?

时间:2016-07-11 22:53:44

标签: php mysql sql pdo

Here is my code:

$token   = $_GET['validate_activate']; // it's something like this "98j34f0j043f094f98325r"
$user_id = $_GET['user_id'];

// db connection here
$stmt = $dbh->prepare("DELETE FROM activate_token WHERE token = :token");
$stmt->execute(array(':token' => $token));

if ( /* deleting is success */ ) {
    // activating the user
} else {
    // your token is invalid
}

Well how can I make a correct condition for that if statement?

3 个答案:

答案 0 :(得分:0)

With the help of rowCount();

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

if ( $stmt->rowCount() ) {
    // activating the user
} else {
    // your token is invalid
}

答案 1 :(得分:0)

This should work, the pdo statement should return True or False if the delete query was successful

if($stmt->execute(array($token = $_GET['validate_activate']))) {
     // activating the user
} else {
    // your token is invalid
}

答案 2 :(得分:0)

$stmt->execute returns a bool result, true if the sql query was successful so just use the result of that in your if statement:

$stmtWorked = $stmt->execute(array($token));
if ($stmtWorked) {
    // activating the user
} else {
    // your token is invalid
}

Also you can use mysqli_stmt_affected_rows() to count for many rows were deleted if you need to know a specific amount.

相关问题