0
$id = $_GET['id'];
$result = mysql_query("select Count(id='$id') As Total from topics"); 

The above code is only working if we put count(id) but i want to get count of selected variable. How to insert id='$id' in count function it is not working please help related this.

arulmr
  • 8,620
  • 9
  • 54
  • 69

6 Answers6

2

You want a where clause in your sql query, which I believe would look like this:

select count(id) As Total from topics where id='$id'

note: depending on what type of column you have for your id field, you might need to drop the single quotes.


Warning

your code is vulnerable to sql injection you need to escape all get, post and request and the better approach will be using Prepared statement

Good Read

  1. How to prevent SQL injection in PHP?
  2. Are PDO prepared statements sufficient to prevent SQL injection?

Note

  1. The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, is officially deprecated as of PHP v5.5.0 and will be removed in the future. So use either PDO or MySQLi

Good read

  1. The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
  2. PDO Tutorial for MySQL Developers
  3. Pdo Tutorial For Beginners
Community
  • 1
  • 1
RobM
  • 3,588
  • 2
  • 19
  • 14
0

Your question isn't very clear but perhaps you're looking for COUNT CASE WHEN id = $id THEN 1 ELSE 0 END (you can even skip the ELSE 0 part I believe).

Helena
  • 623
  • 1
  • 6
  • 12
0

$id get values of $_GET['id']

if you want other data, use $id="your data here"

NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
sheplu
  • 2,937
  • 3
  • 24
  • 21
0

What actually are you trying to do is pretty unclear in the Question. But if you are trying to count the number of rows then simple select count(*) as Total where {your condition} from table will will do for you.

Sandeep.sarkar
  • 130
  • 1
  • 5
0

The following should work:

$id = $_GET['id'];
$result = mysql_query("SELECT COUNT(`" . $id . "`) AS `Total` FROM `Topics`");

But do note that this isn't very secure since it will be vulnerable to SQL Injection attacks.

Jayawi Perera
  • 891
  • 1
  • 8
  • 17
0

Count can be used as below

<?php
$shoes=array("nike","puma","lancer");
echo count($shoes);
?>

Read the documentation in the PHP manual on Count.For inserting id in count:

$result = mysql_query('SELECT COUNT(id) FROM clients'); 
$count = mysql_result($result,0); 
echo $count;
vamsi
  • 329
  • 2
  • 10