Hello
j ai un petit souci que je ne comprends pas.
je n'arrive pas à trouver où est l'erreur.
Dans la base Mysql j ai une liste des noms.
Nom : a2ede2a338d33d483accc3fefc86d958.png
Affichages : 140
Taille : 41,3 Ko
Mais sur le site cela me crée un double de l'avant-dernier, mais n'affiche pas le dernier de la base mysql.
Nom : b0ac1d2e03d1f288e542d5d2cce2297e.png
Affichages : 130
Taille : 11,2 Ko

voici le code complet merci pour l aide :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
 
<?php
// Activer l'affichage des erreurs
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
 
// Configuration de la base de données
$host = '';
$db   = '';
$user = '';
$pass = ''; 
$charset = '4';
 
 
$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);
} catch (\PDOException $e) {
    die("Erreur de connexion : " . $e->getMessage());
}
 
// Création de la table avatars si elle n'existe pas
$pdo->exec("CREATE TABLE IF NOT EXISTS avatars (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL UNIQUE,
    objects TEXT
)");
 
// Création de la table avatar_dates si elle n'existe pas
$pdo->exec("CREATE TABLE IF NOT EXISTS avatar_dates (
    id INT AUTO_INCREMENT PRIMARY KEY,
    avatar_id INT,
    date DATE,
    FOREIGN KEY (avatar_id) REFERENCES avatars(id) ON DELETE CASCADE,
    UNIQUE KEY (avatar_id, date)
)");
 
// Traitement du formulaire
if (isset($_POST["avatar"]) && isset($_POST["objects"])) {
    $avatar = $_POST["avatar"];
    $objects = str_replace("\r\n", "\n", $_POST["objects"]);
 
    $stmt = $pdo->prepare("SELECT * FROM avatars WHERE name = ?");
    $stmt->execute([$avatar]);
    $existingAvatar = $stmt->fetch();
 
if ($existingAvatar) {
    // L'avatar existe déjà, vérifions les objets
    $existingObjects = array_filter(explode("\n", $existingAvatar['objects']), 'trim');
    $newObjects = array_filter(explode("\n", $objects), 'trim');
    $objectsToAdd = array_diff($newObjects, $existingObjects);
 
    // Mettre à jour les objets si nécessaire
    if (!empty($objectsToAdd)) {
        $updatedObjects = implode("\n", array_unique(array_merge($existingObjects, $objectsToAdd)));
        $stmt = $pdo->prepare("UPDATE avatars SET objects = ? WHERE name = ?");
        $stmt->execute([$updatedObjects, $avatar]);
    }
 
    // Ajouter toujours une nouvelle date
    $today = date('Y-m-d');
    $stmt = $pdo->prepare("INSERT IGNORE INTO avatar_dates (avatar_id, date) VALUES (?, ?)");
    $stmt->execute([$existingAvatar['id'], $today]);
 
    echo "Les données de l'avatar ont été mises à jour avec succès.";
} else {
        // Insérer un nouvel avatar
        $stmt = $pdo->prepare("INSERT INTO avatars (name, objects) VALUES (?, ?)");
        $stmt->execute([$avatar, $objects]);
        $avatarId = $pdo->lastInsertId();
 
        // Ajout de la date initiale
        $stmt = $pdo->prepare("INSERT INTO avatar_dates (avatar_id, date) VALUES (?, CURRENT_DATE)");
        $stmt->execute([$avatarId]);
 
        echo "Un nouvel avatar a été enregistré avec succès.";
    }
}
 
// Suppression de toutes les données
if (isset($_POST['delete_all']) && isset($_POST['confirm_delete_all'])) {
    $pdo->exec("DELETE FROM avatar_dates");
    $pdo->exec("DELETE FROM avatars");
    echo "Toutes les données ont été effacées.";
}
 
// Suppression d'un avatar spécifique
if (isset($_POST['delete_avatar']) && isset($_POST['confirm_delete_avatar'])) {
    $avatarId = $_POST['delete_avatar'];
    $stmt = $pdo->prepare("DELETE FROM avatars WHERE id = ?");
    $stmt->execute([$avatarId]);
    echo "L'avatar a été supprimé avec succès.";
}
 
// Définition des dates de filtre
$today = date('Y-m-d');
$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-1 month'));
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : $today;
 
// Récupération des données pour le graphique principal
$stmt = $pdo->prepare("SELECT DATE(date) as date, COUNT(DISTINCT avatar_id) as count 
                       FROM avatar_dates 
                       WHERE date BETWEEN ? AND ? 
                       GROUP BY DATE(date) 
                       ORDER BY date");
$stmt->execute([$startDate, $endDate]);
$chartData = $stmt->fetchAll();
 
// Récupération et comptage des données filtrées
$stmt = $pdo->prepare("
    SELECT DISTINCT a.id, a.name, a.objects,
           GROUP_CONCAT(DISTINCT DATE(ad.date) ORDER BY ad.date DESC SEPARATOR '\n') as dates
    FROM avatars a
    LEFT JOIN avatar_dates ad ON a.id = ad.avatar_id
    WHERE (ad.date BETWEEN ? AND ?) OR ad.date IS NULL
    GROUP BY a.id
    ORDER BY a.id
");
$stmt->execute([$startDate, $endDate]);
$avatars = $stmt->fetchAll();
 
// Initialisation des compteurs
$objectCount = 0;
$NecklaceCount = 0;
$BraceletCount = 0;
$EarringsCount = 0;
$RingCount = 0;
 
// Traitement des avatars et comptage des objets
foreach ($avatars as &$avatar) {
    $objects = array_filter(explode("\n", $avatar['objects']), 'trim');
    $avatar['object_count'] = count($objects);
    $objectCount += $avatar['object_count'];
 
    foreach ($objects as $object) {
        if (stripos($object, "Necklace") !== false) $NecklaceCount++;
        if (stripos($object, "Bracelet") !== false) $BraceletCount++;
        if (stripos($object, "Earrings") !== false) $EarringsCount++;
    }
}
$RingCount = count($avatars);
 
// Préparation des données pour les graphiques
$labels = array_map(function($item) { return $item['date']; }, $chartData);
$data = array_map(function($item) { return $item['count']; }, $chartData);
 
$statsData = [
    ['label' => 'Avatars', 'value' => $RingCount],
    ['label' => 'Necklace', 'value' => $NecklaceCount],
    ['label' => 'Bracelet', 'value' => $BraceletCount],
    ['label' => 'Earrings', 'value' => $EarringsCount]
];
usort($statsData, function($a, $b) {
    return $b['value'] - $a['value'];
});
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Statistiques des Avatars</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="styles.css">
    <script>
    function confirmDeleteAvatar(avatarId, avatarName) {
        if (confirm("Êtes-vous sûr de vouloir supprimer l'avatar '" + avatarName + "' ?")) {
            document.getElementById('confirm_delete_avatar_' + avatarId).value = 'true';
            return true;
        }
        return false;
    }
 
    function confirmDeleteAll() {
        if (confirm("Êtes-vous sûr de vouloir effacer toute la base de données ? Cette action est irréversible.")) {
            document.getElementById('confirm_delete_all').value = 'true';
            return true;
        }
        return false;
    }
 
    var today = '<?php echo $today; ?>';
 
    function setQuickFilter(period) {
        var startDate = document.getElementById('start_date');
        var endDate = document.getElementById('end_date');
 
        endDate.value = today;
 
        switch(period) {
            case 'today':
                startDate.value = today;
                break;
            case 'week':
                startDate.value = formatDate(new Date(new Date(today) - 7 * 24 * 60 * 60 * 1000));
                break;
            case 'month':
                var d = new Date(today);
                startDate.value = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-01';
                break;
            case 'year':
                startDate.value = today.substring(0, 4) + '-01-01';
                break;
            case 'all':
                startDate.value = '2000-01-01';
                break;
        }
 
        startDate.form.submit();
    }
 
    function formatDate(date) {
        var d = new Date(date),
            month = '' + (d.getMonth() + 1),
            day = '' + d.getDate(),
            year = d.getFullYear();
 
        if (month.length < 2) 
            month = '0' + month;
        if (day.length < 2) 
            day = '0' + day;
 
        return [year, month, day].join('-');
    }
    </script>
</head>
<body>
    <div class="container">
        <h1>Statistiques des Avatars</h1>
 
        <div class="filter-form">
            <form method="get">
                <label for="start_date">Date de début:</label>
                <input type="date" id="start_date" name="start_date" value="<?php echo $startDate; ?>">
                <label for="end_date">Date de fin:</label>
                <input type="date" id="end_date" name="end_date" value="<?php echo $endDate; ?>">
                <input type="submit" value="Filtrer"class="delete-btn">
                <div class="quick-filters">
                    <button type="button" onclick="setQuickFilter('today')"class="delete-btn">Aujourd'hui</button>
                    <button type="button" onclick="setQuickFilter('week')"class="delete-btn">Semaine</button>
                    <button type="button" onclick="setQuickFilter('month')"class="delete-btn">Mois</button>
                    <button type="button" onclick="setQuickFilter('year')"class="delete-btn">Année</button>
                    <button type="button" onclick="setQuickFilter('all')"class="delete-btn">Tout</button>
                </div>
            </form>
        </div>
 
        <div class="chart-container">
            <canvas id="statsChart"></canvas>
        </div>
 
        <div class="chart-container">
            <canvas id="avatarChart"></canvas>
        </div>
 
<h2>Liste des objets portés :</h2>
<form method="post" onsubmit="return confirmDeleteAll()">
    <input type="hidden" name="confirm_delete_all" id="confirm_delete_all" value="false">
    <input type="submit" name="delete_all" value="Effacer la base de données" class="delete-btn">
</form>
<div class="stats">
    <p>Nombre d'avatars : <?php echo $RingCount; ?></p>
    <p>Nombre de Bijoux 'Necklace' : <?php echo $NecklaceCount; ?></p>
    <p>Nombre de Bijoux 'Bracelet' : <?php echo $BraceletCount; ?></p>
    <p>Nombre de Bijoux 'Earrings' : <?php echo $EarringsCount; ?></p>
</div>
<hr>
 
<div class="avatars-list">
  <?php foreach ($avatars as $avatar): ?>
    <div class="avatar-card" id="avatar-<?php echo $avatar['id']; ?>">
        <h3 class="avatar-name" onclick="toggleDetails(this)">
            <?php 
            echo htmlspecialchars($avatar['name']); 
            echo " (" . count(array_filter(explode("\n", $avatar['objects']))) . ")";
            ?>
        </h3>
            <div class="avatar-details" style="display: none;">
                <p>Objets:</p>
                <ul>
                <?php
                $objects = array_filter(explode("\n", $avatar['objects']), 'trim');
                foreach ($objects as $object) {
                    echo "<li>" . htmlspecialchars($object) . "</li>";
                }
                ?>
                </ul>
                <p class="date">Dates d'ajout:</p>
                <ul>
                <?php
                $dates = array_filter(explode("\n", $avatar['dates']), 'trim');
                foreach ($dates as $date) {
                    $formattedDate = date('d/m/Y', strtotime($date));
                    echo "<li>" . htmlspecialchars($formattedDate) . "</li>";
                }
                ?>
                </ul>
                <form method="post" class="delete-avatar-form" onsubmit="return confirmDeleteAvatar(<?php echo $avatar['id']; ?>, '<?php echo htmlspecialchars($avatar['name']); ?>')">
                    <input type="hidden" name="delete_avatar" value="<?php echo $avatar['id']; ?>">
                    <input type="hidden" name="confirm_delete_avatar" id="confirm_delete_avatar_<?php echo $avatar['id']; ?>" value="false">
                    <input type="submit" value="Supprimer" class="delete-btn">
                </form>
            </div>
        </div>
    <?php endforeach; ?>
</div>
    </div>
 
   <script>
   function toggleDetails(element) {
    var details = element.nextElementSibling;
    if (details.style.display === "none") {
        details.style.display = "block";
    } else {
        details.style.display = "none";
    }
}
    function confirmDeleteAvatar(avatarId, avatarName) {
        if (confirm("Êtes-vous sûr de vouloir supprimer l'avatar '" + avatarName + "' ?")) {
            document.getElementById('confirm_delete_avatar_' + avatarId).value = 'true';
            return true;
        }
        return false;
    }
 
    function confirmDeleteAll() {
        if (confirm("Êtes-vous sûr de vouloir effacer toute la base de données ? Cette action est irréversible.")) {
            document.getElementById('confirm_delete_all').value = 'true';
            return true;
        }
        return false;
    }
 
    var today = '<?php echo $today; ?>';
 
    function setQuickFilter(period) {
        var startDate = document.getElementById('start_date');
        var endDate = document.getElementById('end_date');
 
        endDate.value = today;
 
        switch(period) {
            case 'today':
                startDate.value = today;
                break;
            case 'week':
                startDate.value = formatDate(new Date(new Date(today) - 7 * 24 * 60 * 60 * 1000));
                break;
            case 'month':
                var d = new Date(today);
                startDate.value = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-01';
                break;
            case 'year':
                startDate.value = today.substring(0, 4) + '-01-01';
                break;
            case 'all':
                startDate.value = '2000-01-01';
                break;
        }
 
        startDate.form.submit();
    }
 
    function formatDate(date) {
        var d = new Date(date),
            month = '' + (d.getMonth() + 1),
            day = '' + d.getDate(),
            year = d.getFullYear();
 
        if (month.length < 2) 
            month = '0' + month;
        if (day.length < 2) 
            day = '0' + day;
 
        return [year, month, day].join('-');
    }
 
    // Configuration du graphique des statistiques
    var statsCtx = document.getElementById('statsChart').getContext('2d');
    var statsChart = new Chart(statsCtx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode(array_column($statsData, 'label')); ?>,
            datasets: [{
                label: 'Statistiques',
                data: <?php echo json_encode(array_column($statsData, 'value')); ?>,
                backgroundColor: [
                    'rgba(192, 57, 43, 0.8)',
                    'rgba(230, 126, 34, 0.8)',
                    'rgba(241, 196, 15, 0.8)',
                    'rgba(52, 152, 219, 0.8)',
                    'rgba(26, 188, 156, 0.8)'
                ],
                borderColor: [
                    'rgba(192, 57, 43, 1)',
                    'rgba(230, 126, 34, 1)',
                    'rgba(241, 196, 15, 1)',
                    'rgba(52, 152, 219, 1)',
                    'rgba(26, 188, 156, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                x: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.1)'
                    }
                },
                y: {
                    grid: {
                        display: false
                    }
                }
            }
        },
        plugins: [{
            afterDraw: function(chart) {
                var ctx = chart.ctx;
                chart.data.datasets.forEach(function(dataset, i) {
                    var meta = chart.getDatasetMeta(i);
                    meta.data.forEach(function(bar, index) {
                        var data = dataset.data[index];
                        var label = chart.data.labels[index];
                        ctx.fillStyle = 'Black';
                        ctx.font = 'bold 12px Arial';
                        ctx.textAlign = 'left';
                        ctx.textBaseline = 'middle';
                        var text = label + ' / ' + data;
                        var padding = 5;
                        var position = bar.tooltipPosition();
                        var xPosition = position.x + padding;
                        var yPosition = position.y;
 
                        if (ctx.measureText(text).width < bar.width - padding * 2) {
                            ctx.fillText(text, xPosition, yPosition);
                        } else {
                            ctx.textAlign = 'left';
                            ctx.fillText(text, bar.x + bar.width + padding, yPosition);
                        }
                    });
                });
            }
        }]
    });
 
    // Configuration du graphique des avatars ajoutés
    var ctx = document.getElementById('avatarChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($labels); ?>,
            datasets: [{
                label: 'Nombre d\'avatars ajoutés',
                data: <?php echo json_encode($data); ?>,
                backgroundColor: 'rgba(92, 64, 51, 0.2)',
                borderColor: 'rgba(92, 64, 51, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
 
    // Gestion de l'affichage des détails des avatars
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.avatar-name').forEach(function(name) {
        name.addEventListener('click', function() {
            var avatarId = this.closest('.avatar-card').id;
            var details = document.querySelector('#' + avatarId + ' .avatar-details');
            if (details.classList.contains('show')) {
                details.classList.remove('show');
            } else {
                details.classList.add('show');
                }
            });
        });
    });
    </script>
</body>
</html>