-1

I have a table table_log filled with logs with different IDs but some of those logs have the same ID. I have to get the sum of column counter of those with the same ID id then display the results a column total_count. This is my query:

SELECT id, SUM(counter) AS total_count FROM table_log GROUP BY id

I have to display this in a table column using PHP. This is what I have:

$sql = "SELECT id, SUM(counter) AS total_count FROM table_log GROUP BY id";
$row = mysql_fetch_assoc($sql);
$sum = $row['total_count'];

$data .= "<td style='width: 200px;' align=center >". $sum ."</td>";

It's not appearing in the table. What should I input instead?

EDIT : I didn't choose to use this. The company did.

Mel
  • 111
  • 1
  • 10
  • You don't actually run the query. Missing `mysql_query()` here, and you should just drop that library and use `mysqli_` or PDO instead. – Qirel Feb 26 '18 at 00:42
  • 1
    Please note the `mysql_` constructor has been **deprecated since 2013 (in PHP 5.5)**, and is **removed in PHP 7 (released in 2015)**. This is because it has **serious security vulnerabilities**. **DO NOT USE IT**. Please consider switching to either [**MySQLi**](http://php.net/manual/en/book.mysqli.php) or [**PDO**](http://php.net/manual/en/book.pdo.php) instead, ensuring that you also use [**prepared statements**](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) to prevent [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) :) – Obsidian Age Feb 26 '18 at 00:42
  • *"I didn't choose to use this. The company did."* - You need to either try and knock some sense into them by using a modern api, or find another employer. *wow*, and in this day and age? What kind of company is this anyway? – Funk Forty Niner Feb 26 '18 at 00:57

1 Answers1

1

Firstly - mysql_* functions are deprecated. Avoid them as much as possible.

Secondly, you need to run the query first, before you can fetch the results.

$conn = mysqli_connect("localhost", "root", "", "db"); //connection string
$q = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($q);

Then it'll work.

man0v
  • 669
  • 3
  • 13
  • it seems to not be working for me still. i've already connected my database – Mel Feb 26 '18 at 01:12
  • @Mel if you are still using `mysql_*` and you can't change to `mysqli` then the syntax will be `$q = mysql_query($sql);` – man0v Feb 26 '18 at 01:13
  • I figured I'd have to delete the 'i' but I guess I'm doing something wrong still :( – Mel Feb 26 '18 at 01:17
  • @Mel not only the "i" but the reference to the connection string as well. See the linked questions at the top of your question for more examples. You are closer to solving it than you think. – man0v Feb 26 '18 at 01:19