Count the records of a single month

1

I am doing a simple consultation to obtain the records of a single month, in my case, the current month. I have a table that saves the date in 17/12/2018 01:12 format since the client asked for it this way.

What I try to do is this:

<?php
$fecha = date('m');
$sql_cuenta = $conn->query("SELECT * FROM prReserv WHERE fecha = '".$fecha."'");

echo "Cantidad de registros este mes: ".$sql_cuenta->rowCount();
?>

But the result I get is 0 when it would have to be 8 , which are the 8 records that are saved. Thanks

    
asked by Stn 17.12.2018 в 05:56
source

2 answers

2

You must format the date field, so that it only takes the necessary month; I leave you as your query should be with an example

<?php
$fecha = date('m');
$sql_cuenta = $conn->query("SELECT COUNT(*) AS Total FROM prReserv WHERE MONTH(fecha) = '".$fecha."'");

?>

What I did was:

  • Assuming that the var% co_of% is worth only the numeric of a month, for example 12
  • I use the function $fecha so that of the column that has your table with the format like this: MONTH() just take the value of 17/12/2018 01:12 then proceed to make the comparison
  • It is assumed that you want to obtain the count of records for a specific month, so it is necessary to use an aggregation function such as 12 that helps to count the values of the table that are previously conditioned for the month that is equal to what you spend
  • UPDATE

    Finally, in order to show the results, you can do something like the following

    $fila = mysqli_fetch_array($sql_cuenta);
    echo $fila["Total"];
    
      

    In the previous code as you can see to be able to print the total of   records of the month in question I used the alias COUNT() that   declare the use of the function Total

        
    answered by 17.12.2018 / 06:05
    source
    1

    You should use Count to count the month records in Mysql for example look like this:

    This is your code:

      

    $ sql_cuenta = $ conn-> query ("SELECT * FROM prReserv WHERE date =   '". $ date."' ");

    and it should be something like this:

    <?php
    
    $query = "SELECT type, COUNT(name) FROM products GROUP BY type"; 
    	 
    $result = mysql_query($query) or die(mysql_error());
    
    //imprimir resultado
    while($row = mysql_fetch_array($result)){
    	echo "There are ". $row['COUNT(name)'] ." ". $row['type'] ." items.";
    	echo "<br />";
    }
    ?>

    If you do not know what count is, it's just a function of Mysql that allows you to count how many data exist in a given rows or rows.

    source in English I still recommend reading Mysql's docs: counting rows

        
    answered by 17.12.2018 в 06:08