smile 22121
smile 22121

Reputation: 295

Return the result of Mysqli execute()

I have a DELETE query, and I want to return the result of the execution. How can I do it ?

My php code:

Function delete_cat($category){
    $stmt = $mysqli->prepare("DELETE category, products FROM category INNER JOIN products WHERE category.id = ? AND product_cat = category.category_name ");
    $stmt->bind_param($category);
    $stmt->execute();
    $stmt->close();
//return should be here

}

Upvotes: 1

Views: 2642

Answers (2)

xAqweRx
xAqweRx

Reputation: 1236

So $stmt->execute(); => returns a bool value, whether your query was successfully executed or not, and you can do it simply like this:

function delete_cat($category){
    $stmt = $mysqli->prepare("DELETE category, products FROM category INNER JOIN products WHERE category.id = ? AND product_cat = category.category_name ");
    $stmt->bind_param($category);
    $result = $stmt->execute();
    $stmt->close();
   return $result;
}

If you needed to get the count of the deleted elements, you can use mysqli_stmt_affected_rows, something like this:

function delete_cat($category){
    $stmt = $mysqli->prepare("DELETE category, products FROM category INNER JOIN products WHERE category.id = ? AND product_cat = category.category_name ");
    $stmt->bind_param($category);
    $stmt->execute();
    $result = $stmt->affected_rows;
    $stmt->close();
   return $result;
}

Upvotes: 4

xate
xate

Reputation: 6379

function delete_cat($category){
    $stmt = $mysqli->prepare("DELETE category, products FROM category INNER JOIN products WHERE category.id = ? AND product_cat = category.category_name ");
    $stmt->bind_param($category);
    $result = $stmt->execute(); // store the return of the method into a variable here so we can return it later
    $stmt->close();
    return $result // would return if the rows have been deleted or not.
    return $mysqli->affected_rows; // would return the amount of rows deleted

}

If you want to get the amount of rows that have been deleted you use affected_rows, if you want to just get the result if the SQL query was performed succesfull, simply store the return of $stmt->execute into a variable and return that.

http://php.net/manual/en/mysqli-stmt.affected-rows.php

http://php.net/manual/de/mysqli-stmt.execute.php

Upvotes: 1

Related Questions