1

I have following PHP script. I want to count and print comments for each article.

The id for each article can be "recalled" by this: <?php echo $listing['Listing']['listing_id'];?> (this return the contentid number)

Now, I have this script:

<?php
          $db =& JFactory::getDBO();
          $query = "SELECT COUNT(comments) AS totalcount WHERE contentid = ????? ";
          $db->setQuery($query);
          $count = $db->loadResult();
echo ($count); ?>

I tried to add in WHERE clause this:

"... WHERE contentid = {$listing['Listing']['listing_id']}"

but $count returns "0" zero. How can I add this variable in the WHERE clause?

Thanks in advance!

1
  • 1
    Did you confirm that the query actually succeeded? Have you output the query string you generated and tried running it manually? Commented Apr 13, 2012 at 18:06

3 Answers 3

2

In the case of an integer:

$query = "SELECT
    COUNT(comments) AS totalcount
WHERE
    contentid = " . ((int) $listing['Listing']['listing_id']);

In the case of a string:

$query = "SELECT
    COUNT(comments) AS totalcount
WHERE
    contentid = " . mysql_real_escape_string($listing['Listing']['listing_id']);

The biggest thing to be weary of is SQL injection. This makes your queries safe. The explicit cast to int will ensure an int value is passed, even if the value is erroneous, at least you wont be open to any attack.

Sign up to request clarification or add additional context in comments.

1 Comment

@Frist van Campen Simply PERFECT! You rock! Thank you!
2

Use sprintf and escape the string.

$query = sprintf("SELECT COUNT(comments) AS totalcount WHERE contentid = '%s'",mysql_real_escape_string($listing['Listing']['listing_id']));

Comments

1

try

$query = "SELECT COUNT(comments) AS totalcount WHERE contentid = '".mysql_real_escape_string($listing['Listing']['listing_id'])."'";

or

$query = "SELECT COUNT(comments) AS totalcount WHERE contentid = ".mysql_real_escape_string($listing['Listing']['listing_id']);

depending on the data type.

4 Comments

Quoting the string... agreed.
Yes, I suggest mysql_real_escape_string($foo) on variables to prevent injection.
Do not use this. appending user-supplied variables is terrible practice.
I don't imagine that an ID would be user supplied, but if it is wrap it with mysql_real_escape_string()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.