-7

I want to find out how many rows in a table of my database meet a certain rule, specifically that "category" matches another variable and "published" is today or earlier. Then I want to simply echo that number.

I have no idea how to go about doing this, though.

I thought I could use count() but I'm not sure how to call just a single column and put the results of each row in an array.

Thanks!

Anfath Hifans
  • 1,588
  • 1
  • 11
  • 20
bababababa
  • 87
  • 1
  • 5

2 Answers2

0

Do this using SQL:

Try this in your database (your columns/tables may be different):

SELECT count(*) FROM blog_posts WHERE category = 'hot_stuff' and published <= NOW();

Then to execute this in PHP, depending on your framework and connection to the database:

    $myCategory = 'hot_stuff';
    $myTable = 'blog_posts';

    $sql = "SELECT count(*) FROM {$myTable} WHERE category = '{$myCategory}' and published <= NOW();";

    $rowCount = $db->query($sql);
    echo $rowCount;
Chris Adams
  • 651
  • 6
  • 8
0
  1. Connect to your database.

    $pdo = new PDO($dsn, $user, $password);
    
  2. Create a prepared statement. This is essential because you need to pass a value for category from your application to the query. It is not necessary to pass a value for the current date because the database can provide that for you. The ? is a placeholder where the parameter you pass will be bound.

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM your_table 
                       WHERE category = ? AND published  <= CURDATE()");
    

    Do not concatenate the parameter into your SQL string (like WHERE category = '$category') because this will create an SQL injection vulnerability.

  3. Execute the prepared statement using your specified value for category.

    $stmt->execute([$category]);   // assuming you have already defined $category
    
  4. Use fetchColumn to return a single value, the count of rows that matched your criteria.

    echo $stmt->fetchColumn();
    
Don't Panic
  • 41,125
  • 10
  • 61
  • 80