Redirect page if PDO database update is success

Viewed 112

Here is a part of the code I am using to update the database. It works, but I would like to redirect the user to another page if the database update is a success. How can I do that ? I know the header('Location: ../../');, but where to use it ?

$statement = $dbconnect->prepare("
   UPDATE members 
   SET name = :fname, lastname = :lname, phone = :phone 
   WHERE member_id = :memberid
");
$dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$statement->execute(
   array(
      ':fname' => "$fname", 
      ':lname' => "$lname", 
      ':phone' => "$phone",
      ':memberid' => "$memberid"
   )
);
} catch(PDOException $e) {
    die("ERROR: Could not connect. " . $e->getMessage());
}

Even tried the following, but no redirection

    $statement->execute(array(':fname' => "$fname", ':lname' => "$lname", ':phone' => "$phone",':memberid' => "$memberid"));

if ($statement) {
   header('Location: http://sitename.com');
} else {
   echo 'It failed!';
}
2 Answers

You need to check the result from the PDOStatement::execute execution and use the correct binding when you execute a prepared statement with an array of insert values (named parameters). Note, that the result from the successful PDO::prepare call is a PDOStatement object, not a boolean value.

The folloling script, based on your code, is a possible solution to your problem:

<?php

try {

    $dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $statement = $dbconnect->prepare("
        UPDATE members 
        SET name = :fname, lastname = :lname, phone = :phone 
        WHERE member_id = :memberid
    ");
    if ($statement === false) {
       die("ERROR: Could not prepare statement.");
    }

    $result = $statement->execute(
        array(
            ':fname' => $fname, 
            ':lname' => $lname, 
            ':phone' => $phone,
            ':memberid' => $memberid
        )
    );
    if ($result) {
        header('Location: http://sitename.com');    
        exit;
    }   
    
} catch(PDOException $e) {

    die("ERROR: Could not connect. " . $e->getMessage());

}

?>

If you want to assume that your update was successful as long as you did not encounter any PDO errors (I assume that updates without errors are successful) you can write this:

$statement = $dbconnect->prepare("UPDATE members SET name = :fname, lastname = :lname, phone = :phone WHERE member_id = :memberid");
$dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$statement->execute(array(':fname' => "$fname", ':lname' => "$lname", ':phone' => "$phone",':memberid' => "$memberid"));

// if there were no errors redirect now
header('Location: ../../');


   } catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}

On another note outside of dev you should find a different way to handle the error: this is almost the same as not having a try/catch.

Related