-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
  • 7,654
  • 4
  • 35
  • 52

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
  • 66,874
  • 43
  • 94
  • 124
Rakesh Sharma
  • 13,570
  • 4
  • 35
  • 42
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
  • 66,874
  • 43
  • 94
  • 124
Jenz
  • 8,172
  • 7
  • 41
  • 75
  • 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
  • 66,874
  • 43
  • 94
  • 124
Birlla
  • 1,520
  • 2
  • 14
  • 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,233
  • 2
  • 24
  • 38
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
  • 36,552
  • 5
  • 55
  • 77