Latest updates
This commit is contained in:
67
get_qid_counts.php
Normal file
67
get_qid_counts.php
Normal file
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
header('Content-Type: application/json');
|
||||
|
||||
// Basic input validation and sanitization
|
||||
if (!isset($_POST['qid']) || empty($_POST['qid'])) {
|
||||
echo json_encode(['error' => 'Missing QID parameter']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$qid = $_POST['qid'];
|
||||
|
||||
// Database connection (adjust credentials accordingly)
|
||||
//
|
||||
$config = require 'config.php';
|
||||
$host = $config['db_host'];
|
||||
$db = $config['db_name'];
|
||||
$user = $config['db_user'];
|
||||
$pass = $config['db_pass'];
|
||||
$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,
|
||||
];
|
||||
|
||||
try {
|
||||
$pdo = new PDO($dsn, $user, $pass, $options);
|
||||
|
||||
$sql = "
|
||||
SELECT value, COUNT(*) AS count
|
||||
FROM Answers
|
||||
WHERE QID = :qid
|
||||
AND value BETWEEN -3 AND 3
|
||||
GROUP BY value
|
||||
ORDER BY value
|
||||
";
|
||||
|
||||
$stmt = $pdo->prepare($sql);
|
||||
$stmt->execute(['qid' => $qid]);
|
||||
$results = $stmt->fetchAll();
|
||||
|
||||
// Initialize array with all possible values from -3 to 3 with zero counts
|
||||
$counts = [];
|
||||
for ($i = -3; $i <= 3; $i++) {
|
||||
$counts[$i] = 0;
|
||||
}
|
||||
|
||||
// Fill in counts from query results
|
||||
foreach ($results as $row) {
|
||||
$counts[(int)$row['value']] = (int)$row['count'];
|
||||
}
|
||||
|
||||
// Return as JSON array of objects [{value: -3, count: 5}, ...]
|
||||
$response = [];
|
||||
foreach ($counts as $value => $count) {
|
||||
$response[] = ['value' => $value, 'count' => $count];
|
||||
}
|
||||
|
||||
echo json_encode($response);
|
||||
|
||||
} catch (PDOException $e) {
|
||||
echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user