Zen
Zen

Reputation: 7385

Having trouble inserting dates into MySQL

I'm trying to insert some dates (a given date, +1 day and +1 month) into MySQL with PHP (CI).

Here is my CI active record code:

the variable $last_period_end returns 2012-02-20, the field it is trying to insert it into is MySQL DATE format.

$data = array(
            'user_id'       =>  $user_id,
            'period_start'  =>  "DATE_ADD($last_period_end, INTERVAL 1 DAY)",
            'period_end'    =>  "DATE_ADD($last_period_end, INTERVAL 1 MONTH)",
            'cost'          =>  $cost
        );

    $result = $this->db->insert('invoices', $data);

    if ( $result )
        return true;
    else
        return false;

This inserts 0000-00-00 rather than what I would like it to.

I have also tried pure SQL:

INSERT INTO betterbill.invoices (user_id, period_start, period_end, cost)
VALUES(18, DATE_ADD(2012-02-20, INTERVAL 1 DAY), DATE_ADD(2012-02-20, INTERVAL 1 MONTH), 100.05);

Interestingly this inserts nothing, rather than 0000-00-00

Any input is appreciated!

Upvotes: 0

Views: 207

Answers (1)

xdazz
xdazz

Reputation: 160833

You miss the quote ' for the date string.

$data = array(
            'user_id'       =>  $user_id,
            'period_start'  =>  "DATE_ADD('$last_period_end', INTERVAL 1 DAY)",
            'period_end'    =>  "DATE_ADD('$last_period_end', INTERVAL 1 MONTH)",
            'cost'          =>  $cost
        );

Upvotes: 2

Related Questions