Lynx
Lynx

Reputation: 1482

How to count number of times a date has been used?

How can I count how many times a date is in a table column using php and mysql?

I am trying to figure out a way to limit the amount of dates can be used for rows

for example:

1   1   0000-00-00  2   yes     2013-10-06 20:07:17 2013-10-06 20:07:17
2   1   0000-00-00  4   yes 1   2013-10-06 20:19:31 2013-10-06 20:19:31
3   1   2013-10-15  2   yes 1   2013-10-06 20:22:14 2013-10-06 20:22:14
4   1   2013-10-30  3   yes 1   2013-10-06 21:07:28 2013-10-06 21:07:28

I want to return an error if 2013-10-30 has been used 5 times.

I am using Laravel 4 and saving the data using a model

    if (<<<<code goes here???>>>>>){
        return Redirect::to('')->withErrors($full)->withInput();
    }

    $schedule->userID = $user->id;
    $schedule->date = $dateFormat;
    $schedule->block = $input['timeslot'];
    $schedule->status = "1";

    $schedule->save();

Upvotes: 0

Views: 97

Answers (2)

trm42
trm42

Reputation: 2676

You could also do something like this:

Schedule::where('timeslot', '=', $date)->count() in addition, if that piece of code is used here and there you could create it as a query scope so you can call it in fashion like Schedule::countForTimeslot($date) anywhere or as a part of more complex query on top of the model.

Upvotes: 1

Casey
Casey

Reputation: 1981

The sql statement you want it is

SELECT COUNT (id) FROM table WHERE DATE(date_field) = :date

don't use rowCount that should be used to count row affected (like in a delete or update)

Upvotes: 1

Related Questions