«

PHP列出某字段重复值和次数

刚子 发布于 阅读:85


<?php

$host = 'localhost';
$db   = 'DBNAME';
$user = 'UNAME';
$pass = 'MIMA';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);

    // 假设我们要检查的字段名为 'column_name' 所在的表为 'table_name'
    $sql = "SELECT file, COUNT(*) 
            FROM fa_video 
            GROUP BY file 
            HAVING COUNT(*) > 1";

    $stmt = $pdo->query($sql);

    while ($row = $stmt->fetch()) {
        echo "重复值: " . $row['file'] . " 出现次数: " . $row['COUNT(*)'] . "<br>";
    }
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>