How to count the number of rows with a date from a certain year in CodeIgniter?

白昼怎懂夜的黑 提交于 2021-01-20 08:59:24

问题


I have the following query.

$query = $this->db->query('SELECT COUNT(*) FROM iplog.persons WHERE begin_date LIKE '2014%'');

I need to count the number of columns with a begin_date in the year 2014.

When I run this script I'm getting an error:

Parse error: syntax error, unexpected '2014' (T_LNUMBER) in C:\xampp\htdocs\iPlog2\application\controllers\stat.php on line 12

I was trying to change my CI script to

$query = $this->db->query('SELECT COUNT(*) FROM iplog.persons WHERE begin_date LIKE "2014%"');

but it caused an error.


回答1:


You mean, count ROWS:

So for that, just count the number of rows you have based on a condition:

$year = '2014'
$this->db->from('iplog');
$this->db->like('begin_date', $year); 
$query = $this->db->get();
$rowcount = $query->num_rows();



回答2:


First, you have a simple typo regarding the use of single quotes. Your complete sql string should be double quoted so that your value-quoting can be single quoted.

Second, you are using inappropriate query logic. When you want to make a comparison on a DATE or DATETIME type column, you should NEVER be using LIKE. There are specific MYSQL functions dedicated to handling these types. In your case, you should be using YEAR() to isolate the year component of your begin_date values.

Resource: https://www.w3resource.com/mysql/date-and-time-functions/mysql-year-function.php

You could write the raw query like this: (COUNT(*) and COUNT(1) are equivalent)

$count = $this->db
              ->query("SELECT COUNT(1) FROM persons WHERE YEAR(begin_date) = 2014")
              ->row()
              ->COUNT;

Or if you want to employ Codeigniter methods to build the query:

$count = $this->db
              ->where("YEAR(begin_date) = 2014")
              ->count_all_results("persons");

You could return all of the values in all of the rows that qualify, but that would mean asking the database for values that you have no intention of using -- this is not best practice. I do not recommend the following:

$count = $this->db
              ->get_where('persons', 'YEAR(begin_date) = 2014')
              ->num_rows();

For this reason, you should not be generating a fully populated result set then calling num_rows() or count() when you have no intention of using the values in the result set.




回答3:


Replace quotes like this :

$query = $this->db->query("SELECT COUNT(*) FROM iplog.persons WHERE begin_date LIKE '2014%'");

Double quote your entire query, then simple quote your LIKE criteria.



来源:https://stackoverflow.com/questions/28744460/how-to-count-the-number-of-rows-with-a-date-from-a-certain-year-in-codeigniter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!