I am trying to display user ID, username and the count of subscriptions they purchased every year. My database contain two tables namely subscriptions and users as follows:
users
user_id | name | phone_number |
---|---|---|
1 | xyz | 4567890 |
2 | abc | 4578003 |
subscriptions
subc_id | user_id | type | start_time |
---|---|---|---|
1 | 2 | week | 2019-07-30 17::00:19 |
2 | 4 | year | 2020-05-12 22:38:24 |
SQL query i am using in my php code is
SELECT subscriptions.user_id, users.name, COUNT(CASE WHEN YEAR(subscriptions.start_time) = "2018" AND subscriptions.type = "year" THEN 1 END) AS "2018",COUNT(CASE WHEN YEAR(subscriptions.start_time) = "2019" AND subscriptions.type = "year" THEN 1 END) AS "2019",COUNT(CASE WHEN YEAR(subscriptions.start_time) = "2020" AND subscriptions.type = "year" THEN 1 END) AS "2020",COUNT(CASE WHEN YEAR(subscriptions.start_time) = "2021" AND subscriptions.type = "year" THEN 1 END) AS "2021" FROM subscriptions, users WHERE subscriptions.user_id = users.user_id
Problem is it's working fine in my phpmyadmin SQL query interface but when i use it with php mysqli it gives me following error
Parse error: syntax error, unexpected '2018' (T_LNUMBER)
Kindly tell me what is wrong with my code. My php code is
<?php
$sql = "SELECT subscriptions.user_id, users.name, COUNT(CASE WHEN YEAR(subscriptions.start_time) = "2018" AND subscriptions.type = "year" THEN 1 END) AS "2018",COUNT(CASE WHEN YEAR(subscriptions.start_time) = "2019" AND subscriptions.type = "year" THEN 1 END) AS "2019",COUNT(CASE WHEN YEAR(subscriptions.start_time) = "2020" AND subscriptions.type = "year" THEN 1 END) AS "2020",COUNT(CASE WHEN YEAR(subscriptions.start_time) = "2021" AND subscriptions.type = "year" THEN 1 END) AS "2021" FROM subscriptions, users WHERE subscriptions.user_id = users.user_id";
if ($res = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($res) > 0) {
echo "<table>";
echo "<tr>";
echo "<th>user_id</th>";
echo "<th>Name</th>";
echo "<th>2018</th>";
echo "<th>2019</th>";
echo "<th>2020</th>";
echo "<th>2021</th>";
echo "<tr>";
while($row = mysqli_fetch_array($res))
{
echo "<tr>";
echo "<td>" . $row['user_id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['2018'] . "</td>";
echo "<td>" . $row['2019'] . "</td>";
echo "<td>" . $row['2020'] . "</td>";
echo "<td>" . $row['2021'] . "</td>";
echo "</tr>";
}
echo "<table>";
}
else {
echo "No Records";
}
}
?>