Undefined Property: Dateperiod::$format

Asked

Viewed 30 times

-3

I am making a system that registers a set of dates via $_POST. I want to insert in the database the range created below via datetime. But when executing appears the above message. How to proceed? The error appears in the $sql statement.

    $start = new DateTime($_POST["data1"]); //nova data começo
    $end = new DateTime($_POST["data2"]); // final da data

    $interval = new DateInterval("P1D"); //intervalo de datas no periodo de um dia

    $period = new DatePeriod($start, $interval, $end); //periodo no começo da data, intervalo e final da data

    try
    {
        $connection = new PDO("mysql:host=localhost;dbname=php","root","");
        $connection->exec("set_names_utf8");
    }
    catch(PDOExeption $e)
    {
        echo "Erro" . $e->getMessage();
    }

    $sql = "INSERT INTO datas(datas) VALUES('$period->format('d-m-Y')')";
    $x = $connection->prepare($sql);
    $x->execute();

1 answer

0


Error says it is not possible to use the method format. You are using the object the wrong way. Check in the documentation of DatePeriod the available methods:

DatePeriod implements Traversable {

    /* Constants */
    const integer EXCLUDE_START_DATE = 1 ;

    /* Properties */
    public integer $recurrences ;
    public boolean $include_start_date ;
    public DateTimeInterface $start ;
    public DateTimeInterface $current ;
    public DateTimeInterface $end ;
    public DateInterval $interval ;

    /* Methods */
    public __construct ( DateTimeInterface $start , DateInterval $interval , int $recurrences [, int $options ] )
    public __construct ( DateTimeInterface $start , DateInterval $interval , DateTimeInterface $end [, int $options ] )
    public __construct ( string $isostr [, int $options ] )
    public getDateInterval ( void ) : DateInterval
    public getEndDate ( void ) : DateTimeInterface
    public getRecurrences ( void ) : int
    public getStartDate ( void ) : DateTimeInterface
}

What you may be trying to do is enter both dates in the bank. If so, you can use $period->getStartDate()->format('...') and $period->getEndDate()->format('...').

There are other problems with your code. It is subject to SQL Injection and it is important that you handle your system’s data entries, and improve how you build your queries. The questions below will help you:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.