row(s) affected in mysql update with PHP

前端 未结 10 1848
臣服心动
臣服心动 2020-12-10 14:08

How do i find if my update is successful or not? i update using a where uniqueName=name so i should always only update 0 rows or 1. What is a good way to check if i updated

相关标签:
10条回答
  • 2020-12-10 14:27

    I'm pretty late here, but you could always force a failure on no match by changing your query.

    For table 'foo' with columns 'ID' and 'value'. Match expression: ID = 4

    update foo
    join (select ID as nearID,
    ID = 4
    as matched from foo order by matched desc limit 0, 1) as t on nearID = ID
    set value='somedata2'    
    , ID = if(matched, nearID, 'nomatch')
    

    It's probably easier just to change the table to include either an update timestamp or sequence number instead though. (since those would change on every update)

    0 讨论(0)
  • 2020-12-10 14:29

    If using PDO, affected rows can be obtained using rowCount() function as below:

    /* Delete all rows from the FRUIT table */
    $del = $dbh->prepare('DELETE FROM fruit');
    $del->execute();
    
    /* Return number of rows that were deleted */
    print("Return number of rows that were deleted:\n");
    $count = $del->rowCount();
    print("Deleted $count rows.\n");
    
    0 讨论(0)
  • 2020-12-10 14:30

    mysql_affected_rows() will return the number of rows affected by your update.

    http://us.php.net/manual/en/function.mysql-affected-rows.php

    0 讨论(0)
  • 2020-12-10 14:33

    if your update query is in a variable named $query, you can do;

    $result = mysql_query($query);
    if($result){
        //succes!
    } else {
        //fail!
    }
    

    Hope this helps. If you just want to know if your query was executed succesfully, this will do. If you really want to know how many rows are affected, use the other suggestions.

    0 讨论(0)
  • 2020-12-10 14:36

    mysql_affected_rows($link) is correct but depreciated.. mysqli_affected_rows($link) should be used now.

    http://php.net/manual/en/function.mysql-affected-rows.php

    0 讨论(0)
  • 2020-12-10 14:37

    try using mysql_affected_rows([$link])

    0 讨论(0)
提交回复
热议问题