简体   繁体   中英

PHP Delete function is deleting database row, but response is showing error?

I have created a PHP file called DB_Functions which contains my Delete method for removing a database row by User Id. Code:

    //Delete User
public function deleteUser($id){

    $stmt = $this->conn->prepare("DELETE FROM users WHERE user_id = ?");
    $stmt->bind_param("s", $id);
    $result = $stmt->execute();
    $stmt->close();
}

I have then created another PHP file to act as an endpoint which calls this function after the Id is received as a POST parameter. Code:

require_once 'include/DB_Functions.php';
$db = new DB_Functions();

//json response array
$response = array();

if(isset($_POST['id'])){

//recieve GET parameters
$id = $_POST['id'];

$result = $db->deleteUser($id);
if($result){
    $response["error"] = FALSE;
    $response["message"] = "User deleted succesfully";
}else{
    $response["error"] = TRUE;
    $response["error_msg"] = "User did not delete";
}
echo json_encode($response);
}

When testing this using Advanced Rest Client and when using with an Andriod development I am working on, the row is deleted from the database but the parsed response in ARC is the error message and in the Android Logcat the same response message of "User did not delete" is shown?

Any help?

Your function does not return any value, so when being compiled automatically returns a NULL value, which is why the error is always shown.

You need to add a return statement.

In your deleteUser function you are missing return statement. If you do not return anything then function will always return null .

So, In your case it's returning NULL and in further condition check it's going to else case.

public function deleteUser($id){

    $stmt = $this->conn->prepare("DELETE FROM users WHERE user_id = ?");
    $stmt->bind_param("s", $id);
    $result = $stmt->execute();
    $stmt->close();
    return $result;  // add this
}

Return the result in the function...

public function deleteUser($id){
    $stmt = $this->conn->prepare("DELETE FROM users WHERE user_id = ?");
    $stmt->bind_param("s", $id);
    $result = $stmt->execute();
    $stmt->close();
    return $result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM