Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

php - Redirect page if PDO database update is success

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!';
}
question from:https://stackoverflow.com/questions/65557863/redirect-page-if-pdo-database-update-is-success

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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());

}

?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...