简体   繁体   English

PHP / MySQL:查询正确执行,受影响的行返回-1

[英]PHP / MySQL: query is executed properly, affected_rows returns -1

I'm trying to delete a row from a table, and check if it worked / if a row has been found and removed.我正在尝试从表中删除一行,并检查它是否有效/是否找到并删除了一行。 I use the following query to do so: DELETE FROM TableName WHERE val1=1 AND val2=2 AND val3=3 .我使用以下查询来执行此操作: DELETE FROM TableName WHERE val1=1 AND val2=2 AND val3=3 I send that code via the connection $conn using a prepare and execute function, and it works just fine.我使用准备和执行函数通过连接$conn发送该代码,它工作得很好。 The row I'm looking for is being found and deleted.正在查找并删除我要查找的行。 But if I want to check if it worked using $conn->affected_rows it returns -1, which means that an error occured.但是如果我想检查它是否使用$conn->affected_rows它返回 -1,这意味着发生了错误。 I don't understand, where the error could be, that affected_rows returns -1, even though the query has been executed properly...我不明白错误可能在哪里,即使查询已正确执行, affected_rows返回 -1...

If you do not understand the issue, feel free to ask in a comment.如果您不明白该问题,请随时在评论中提问。

code:代码:

$query = "DELETE FROM ComTasks WHERE comid=? AND obj=? AND type=0";
$response = paramQuery($conn, $query, array($communityid, $userid), "ss");
echo $conn->affected_rows; //=> -1

function paramQuery($conn, $query, $params, $str){
    if(!is_array($params)) $params = array($params);
    $stmt = $conn->prepare($query);
    if($stmt === false) return -1;
    for($i=0; $i<count($params); $i++){
        $params[$i] = &$params[$i];
    }
    array_unshift($params, $str);
    call_user_func_array(array($stmt, 'bind_param'), $params);
    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->close();
    return $result;
}

Since you are using a prepared statement and $stmt, the affected_rows should also be called from $stmt:由于您使用的是准备好的语句和 $stmt,也应该从 $stmt 调用受影响的行:

$stmt->affected_rows;

However since you wrapped it in a function, and do a $stmt-close(), this will not work outside of the function call.但是,由于您将其包装在一个函数中,并执行了 $stmt-close(),因此在函数调用之外这将不起作用。 You may have to adjust your function to store that value before close, and before the return of the function.您可能需要调整您的函数以在关闭之前和函数返回之前存储该值。

Some more info here on php manual: http://php.net/manual/en/mysqli-stmt.affected-rows.php有关 php 手册的更多信息: http : //php.net/manual/en/mysqli-stmt.affected-rows.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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