简体   繁体   中英

Mysql Count issue with variable in sql statement - php

If I use a variable in a php SQL statement that also has COUNT, I get an error. If use a literal number instead of the variable, it works fine. In the code below, you can see where I set my variable. It's set to "test2", first line of code below.

What am I doing wrong?

//$tag_text_ipb hardcoded here for testing    
$tag_text_ipb="test2";  

//when I replace $tag_text_ipb with the literal 'test2' in SQL below, it works fine.
$query_total_tags = "SELECT COUNT(1) FROM core_tags WHERE tag_meta_app = 'downloads' AND tag_text = $tag_text_ipb"; 

$dlresult_total_tags = mysql_query( $query_total_tags );

//Mysql reports an error here (see below for the error text) ONLY when I use the $tag_text_ipb variable in the SQL statement.
$tag_count= mysql_result($dlresult_total_tags,$k[COUNT(1)]);  

The error is: Warning: mysql_result(): supplied argument is not a valid MySQL result resource in /home/ipboard/admin/... : eval()'d code on line 3884

This error disappears and everything works properly if I use a literal in the SQL statement instead of $tag_text_ipb.

You're missing quotes around the tag text var in your SQL. Should be like this:

$query_total_tags = "SELECT COUNT(1) FROM core_tags WHERE tag_meta_app = 'downloads' AND tag_text = '".$tag_text_ipb."'"; 
$query_total_tags = "SELECT COUNT(1) ... AND tag_text = '$tag_text_ipb'"; 
                                                        ^             ^  

You need to quote the text values, otherwise your query will be malformed. Please do read about SQL injection, and see if you can use bind parameters rather than raw queries.

try this

$query_total_tags = "SELECT COUNT(1) FROM core_tags WHERE tag_meta_app = 'downloads' AND tag_text = '$tag_text_ipb'"; 

(single qoutes around $tag_text_ipb)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM