`print_r($mysqli,1)` changes `$mysqli->affected_ro

2020-04-17 04:57发布

问题:

I was using user-assert functions like :

debug_assert (
    gettype($ob)=='object', 
    "Not an object <pre>"
        .print_r($ob,1).'</pre>' 
    ) or exit;

but i found out that print_r changes results of $mysqli->affected_rows 's when called on $mysqli : it resets affected_rows from previous 'n' to -1.

Test code :

$q= "INSERT INTO t_envois SET id_contact=243";

if (!$mysqli) die ("missing mysqli");
$ok = $mysqli->query($q);
if (!$ok) die ("bad query $q : ".$mysqli->errno.") ".$mysqli->error);

function get_affected_rows() {
    global $mysqli;
    return $mysqli->affected_rows;
}

echo "1) ".($mysqli->affected_rows)."<br>"; // 1
echo "2) ".($mysqli->affected_rows)."<br>"; // 1
echo "3) ".get_affected_rows()."<br>";    // 1 try other function
echo "4) ".get_affected_rows()."<br>";    // 1 (no issue)
echo "5) ".(print_r($mysqli,1))."<br>";    // affected_rows shown as 1
echo "6) ".($mysqli->affected_rows)."<br>"; // -1 CHANGED !!
echo "7) ".get_affected_rows()."<br>";    // -1 etc

How can the result change from 1 to -1 when print_r is called ? Are there other non-sql functions that change $mysqli fields ? Is there a way to avoid this ?

回答1:

As @Progman stated it's related to a long standing php bug : http://bugs.php.net/bug.php?id=67348

stat, print_r, var_dump and possibly other function that call 'stat' do reset affected_rows to -1.

In my case the workaround has been to rewrite a fixed print_r-like function :

function print_it($thing) {
    if ((gettype ($thing) == 'object') 
        and (get_class($thing) == 'mysqli'))
        echo "...\naffected_rows => ".$thing->affected_rows."...";
    else 
        print_r($thing);
}


标签: php mysqli