Hardik Dave
Hardik Dave

Reputation: 706

PAssing PHP variables inside a mysql_query function

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.

Upvotes: 0

Views: 674

Answers (3)

Marc B
Marc B

Reputation: 360572

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.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

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

Upvotes: 2

Companjo
Companjo

Reputation: 1792

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.'

Upvotes: 0

Related Questions