How to remove htmlentities() values from the database?

前端 未结 6 1681
星月不相逢
星月不相逢 2021-02-08 04:42

Long before I knew anything - not that I know much even now - I desgined a web app in php which inserted data in my mysql database after running the values through htmlent

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-08 04:53

    This is my bullet proof version. It iterates over all Tables and String columns in a database, determines primary key(s) and performs updates.

    It is intended to run the php-file from command line to get progress information.

    set_charset("utf8");
    
    $tables = $DBC->query("SHOW FULL TABLES WHERE Table_type='BASE TABLE'");
    while($table = $tables->fetch_array()) {
        $table = $table[0];
        $columns = $DBC->query("DESCRIBE `{$table}`");
        $textFields = array();
        $primaryKeys = array();
        while($column = $columns->fetch_assoc()) {
            // check for char, varchar, text, mediumtext and so on
            if ($column["Key"] == "PRI") {
                $primaryKeys[] = $column['Field'];
            } else if (strpos( $column["Type"], "char") !== false || strpos($column["Type"], "text") !== false ) {
                $textFields[] = $column['Field'];
            }
        }
        if (!count($primaryKeys)) {
            echo "Cannot convert table without primary key: '$table'\n";
            continue;
        }
        foreach ($textFields as $textField) {
            $sql = "SELECT `".implode("`,`", $primaryKeys)."`,`$textField` from `$table` WHERE `$textField` like '%&%'";
            $candidates = $DBC->query($sql);
            $tmp = $DBC->query("SELECT FOUND_ROWS()");
            $rowCount = $tmp->fetch_array()[0];
            $tmp->free();
            echo "Updating $rowCount in $table.$textField\n";
            $count=0;
            while($candidate = $candidates->fetch_assoc()) {
                $oldValue = $candidate[$textField];
                $newValue = html_entity_decode($candidate[$textField], ENT_QUOTES | ENT_XML1, 'UTF-8');
                if ($oldValue != $newValue) {
                    $sql = "UPDATE `$table` SET `$textField` = '"
                        . $DBC->real_escape_string($newValue)
                        . "' WHERE ";
                    foreach ($primaryKeys as $pk) {
                        $sql .= "`$pk` = '" . $DBC->real_escape_string($candidate[$pk]) . "' AND ";
                    }
                    $sql .= "1";
                    $DBC->query($sql);
                }
                $count++;
                echo "$count / $rowCount\r";
            }
        }
    }
    ?>
    

    cheers Roland

提交回复
热议问题