0

I want to pass a php variable in 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.

4
  • Use PDO or mysqli and prepared statements: SELECT count(*) FROM comments WHERE img_id = ? Commented Apr 4, 2014 at 15:53
  • 1
    You are entirely misusing the mysql functions. What tutorial are you using to teach you? Commented Apr 4, 2014 at 15:53
  • @Jeroien: Could you provide some more insights on using PDO/mysqli function for this problem. How can I write the code for the same? Commented Apr 4, 2014 at 15:54
  • You should start with a tutorial or the php manual, there are plenty of examples there. Commented Apr 4, 2014 at 15:57

3 Answers 3

2

As the colour coding will show you, your query is wrong. You could also debug it by just echoing your query:

SELECT count(*) FROM comments WHERE img_id =  '.217.'

Clearly incorrect!

$tty = '217';   

$sql = mysql_query("SELECT count(*) FROM comments WHERE img_id = ".intval($tty));
$row = mysql_fetch_row($sql);
$number = $row[0];
echo $number;

Alternative one-liner for getting the value:

list($number) = mysql_fetch_row(mysql_query("select count(*) from `comments` where `img_id`=".intval($tty)));
Sign up to request clarification or add additional context in comments.

2 Comments

How can I echo the list($number) i.e the count that I get from the sql query?
This still returns a 0
0

This should work:

$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 ;

Use '".$tty."' instead of '.$tty.'

Comments

0

Basic PHP syntax:

$num_of_comments = mysql_query("[[...snip...]]=  '.$tty.'");

You never "closed" your string, so you're trying to execute a PHP concatenation INSIDE your string, which won't work. Your query string is literally going to be

WHERE imd_id = '.217.'
                ^---^--- note the concatentation operators

For a "-quoted string, you do NOT need to concatenate:

$num_of_comments = mysql_query([[..snip..] =  '$tty'");
                                              ^^^^^^^---note: no dots

is all you need.

2 Comments

is all you need... if you want a visit from Bobby Tables.
Tempted to post one of your own enjoy having your server pwn3d comments ;-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.