要使用 PHP exec
函數處理用戶留存率,您需要首先確定如何計算用戶留存率。用戶留存率通常是指在特定時間段內新用戶中有多少百分比在后續時間段內仍然在使用產品或服務。
假設您有一個數據庫表,其中包含以下字段:
user_id
:用戶的唯一標識符created_at
:用戶注冊日期和時間retained_at
:用戶首次進行有價值互動(例如購買、訂閱等)的日期和時間要計算用戶留存率,您可以使用以下 SQL 查詢:
SELECT
DATE(created_at) AS date,
COUNT(DISTINCT user_id) AS new_users,
COUNT(DISTINCT CASE WHEN retained_at IS NOT NULL THEN user_id END) AS retained_users,
(COUNT(DISTINCT CASE WHEN retained_at IS NOT NULL THEN user_id END) / COUNT(DISTINCT user_id)) * 100 AS retention_rate
FROM
users
GROUP BY
DATE(created_at)
ORDER BY
DATE(created_at);
然后,您可以使用 PHP 的 exec
函數執行此查詢并處理結果。以下是一個示例:
<?php
// 數據庫連接信息
$host = 'localhost';
$db = 'your_database';
$user = 'your_username';
$pass = 'your_password';
$charset = 'utf8mb4';
// 創建 PDO 連接
$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,
];
$pdo = new PDO($dsn, $user, $pass, $options);
// 執行 SQL 查詢
$sql = "
SELECT
DATE(created_at) AS date,
COUNT(DISTINCT user_id) AS new_users,
COUNT(DISTINCT CASE WHEN retained_at IS NOT NULL THEN user_id END) AS retained_users,
(COUNT(DISTINCT CASE WHEN retained_at IS NOT NULL THEN user_id END) / COUNT(DISTINCT user_id)) * 100 AS retention_rate
FROM
users
GROUP BY
DATE(created_at)
ORDER BY
DATE(created_at);
";
$stmt = $pdo->query($sql);
// 處理查詢結果
$retentionRates = [];
while ($row = $stmt->fetch()) {
$date = $row['date'];
$newUsers = $row['new_users'];
$retainedUsers = $row['retained_users'];
$retentionRate = $row['retention_rate'];
// 將結果存儲到數組中
$retentionRates[$date] = [
'new_users' => $newUsers,
'retained_users' => $retainedUsers,
'retention_rate' => $retentionRate,
];
}
// 輸出結果
foreach ($retentionRates as $date => $data) {
echo "Date: $date\n";
echo "New Users: {$data['new_users']}\n";
echo "Retained Users: {$data['retained_users']}\n";
echo "Retention Rate: {$data['retention_rate']}%\n\n";
}
?>
請注意,這個示例使用了 PDO 來連接數據庫并執行查詢。您可以根據您的實際情況使用其他數據庫擴展(如 mysqli)或數據庫抽象庫(如 Doctrine)。