-1

I want to pass a php variable to mysql_query such as:

$tty = '217';   

$num_of_comments = mysql_query("SELECT count(*) FROM comments WHERE img_id =  '.$tty.'");
$num_of_comments1 = mysql_fetch_array($num_of_comments);
$num_of_comments2 = $num_of_comments1[0];
echo $num_of_comments2 ;

However, I am not able to get the value needed in num_of_comments2. It returns a 0 on echo. Also I tried hardcoding 217 in the place of $tty in the query. There it works.

I am also aware that this problem can be solved by mysqli/PDO. Can someone be kind enough to help me with the code in that case?

Michael Dunn
  • 8,163
  • 4
  • 37
  • 54

5 Answers5

0

you have adding extra dots in query try below

$num_of_comments = mysql_query("SELECT count(*) FROM comments WHERE img_id = '$tty'");

This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the Prepared Statements of MySQLi or PDO_MySQL extensions should be used to ward off SQL Injection attacks !

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
Rakesh Sharma
  • 13,680
  • 5
  • 37
  • 44
0

You have error in your sql. Try with this.

$num_of_comments = mysql_query("SELECT count(*) FROM comments WHERE img_id ='$tty'");

This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the Prepared Statements of MySQLi or PDO_MySQL extension should be used to ward off SQL Injection attacks !

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
Jenz
  • 8,280
  • 7
  • 44
  • 77
  • Why downvote for this solution? .The query will definitely won't work due to the extra dot in it. – Jenz Apr 05 '14 at 05:45
0

Follow this

Replace

 $num_of_comments = mysql_query("SELECT count(*) FROM comments WHERE img_id =  '.$tty.'");

with this

 $num_of_comments = mysql_query("SELECT count(*) FROM comments WHERE img_id ='$tty'");

This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the Prepared Statements of MySQLi or PDO_MySQL extension should be used to ward off SQL Injection attacks !

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
Birlla
  • 1,700
  • 2
  • 15
  • 17
0

try this

$tty = '217';   

$num_of_comments = mysql_query("SELECT count(*) FROM comments WHERE img_id =$tty");
$num_of_comments1 = mysql_fetch_array($num_of_comments);
$num_of_comments2 = $num_of_comments1[0];
echo $num_of_comments2 ;
user1844933
  • 3,296
  • 2
  • 25
  • 42
0

you have to make difference between fetch_array or fetch_num

try this:

 $tty = '217';   

 $num_of_comments = mysql_query("SELECT count(*) as counts FROM comments WHERE img_id =  '".$tty."' ");
 $num_of_comments1 = mysql_fetch_array($num_of_comments);
 $num_of_comments2 = $num_of_comments1['counts'];
 echo $num_of_comments2 ;
echo_Me
  • 37,078
  • 5
  • 58
  • 78