John
John

Reputation: 952

PHP script is not executing my statement

I am trying to post my form with PHP. But by some reason my PHP script is not posting. When I turn error reporting on I get the following errors:

Notice: Undefined index: date2
Notice: Undefined variable: newSingle_cal6
Warning: Cannot modify header information - headers already sent 

I think none of these errors are causing the problem. The scripts sends me to header('Location: ../error.php'); which means the script is not executed. Also when I look in phpmyadmin, I see that the database is not updated.

I have tried to execute the SQL statement in mysql and the sql statement is working.

Does someone know what is wrong in my script and how I can fix the problem?

Here is my full script:

<?php
    include_once('../../../../includes/db_connect.php');
    include_once('../../../../includes/functions.php');
    sec_session_start();

$correct = true;

$_SESSION['user_id'];
$pers_id = $_POST['pers_id'] ;
$name = $_POST['name'] ;
$single_cal4 = $_POST['date1'] ;
$single_cal6 = $_POST['date2'] ;

try {
    $myDateTime1 = DateTime::createFromFormat('d/m/Y', $single_cal4);
} catch (Exception $e) {
    echo $e->getMessage();
}
$newSingle_cal4 = $myDateTime1->format('Y-m-d');
if(!empty($_POST['date2'])){
    try {
        $myDateTime3 = DateTime::createFromFormat('d/m/Y', $single_cal6);
    } catch (Exception $e) {
        echo $e->getMessage();
    }
    $newSingle_cal6 = $myDateTime3->format('Y-m-d');
}

if($correct){
    $db = new PDO('mysql:host=localhost;dbname=db', 'root', '');

$query = "INSERT INTO cus(user_id, pers_id, name, date1, date2) VALUES (?, ?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->execute(array($_SESSION['user_id'], $pers_id, $name, $newSingle_cal4, $newSingle_cal6));

            header('Location: ../success.php');
}else{
            header('Location: ../error.php');
}
?>

Upvotes: 0

Views: 266

Answers (1)

Tony
Tony

Reputation: 3068

There's a few issues here:

Notice: Undefined index: date2

This is because the index date2 does not exist in your post ($_POST['date2'])

Notice: Undefined variable: newSingle_cal6

Because date2 does not exist in your post the variable newSingle_cal6 is never set.

Warning: Cannot modify header information - headers already sent

This is because the headers on your page have already been sent before you call header('Location: ../success.php');. This will happen if you call header or echo before that. The headers will also send if you have any raw non-php text in your file before. Make sure there is no space or anything before your opening php tag (<?php).

Find more information on this error here.

Upvotes: 1

Related Questions