4

After submitting information to my database, I want to refresh the page to show those changes, as when the form has been processed. The page "reloads" after submission but does not reflect the changes, so I assumed I would need to add a refresh command in when submit is pressed, but it seems to be too quick?

So I added a refresh time, but even cranking it up to 50 I got the same result.

If I press the button twice it refreshes with the correct information. Is there a better way to do this?

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

include_once '../includes/conn.php';

if(!$user->is_loggedin()){
    $user->redirect('../users/login.php');
}

$id = $_SESSION['session'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id=:id");
$stmt->execute(array(":id"=>$id));

$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
$location = isset($_POST['location']) ? $_POST['location'] : '';
$about = isset($_POST['about']) ? $_POST['about'] : '';
$title = isset($_POST['title']) ? $_POST['title'] : '';

if($title!=''){
    $sql = "UPDATE users SET title=:title WHERE id=:id";    
    $stmt = $conn->prepare($sql); 
    if($stmt == false){ 
        $error = "User Title update failed. Please try again.";
    } 

    $result = $stmt->execute(array(":title"=>$title, ":id"=>$id));

    if($result == false) { 
        $error = "User Title update failed. Please try again.";
    } 
    $count = $stmt->rowCount();
} 

if($location!=''){
    $sql = "UPDATE users SET location=:location WHERE id=:id";  
    $stmt = $conn->prepare($sql); 
    if($stmt == false){ 
        $error = "User Location update failed. Please try again.";
    } 

    $result = $stmt->execute(array(":location"=>$location, ":id"=>$id));

    if($result == false) { 
        $error = "User location update failed. Please try again.";
    } 
    $count = $stmt->rowCount();
} 

if($about!=''){
    $sql = "UPDATE users SET about=:about WHERE id=:id";    
    $stmt = $conn->prepare($sql); 
    if($stmt == false){ 
        $error = "about Me update failed. Please try again.";
    } 

    $result = $stmt->execute(array(":about"=>$about, ":id"=>$id));

    if($result == false) { 
        $error = "about Me location update failed. Please try again.";
    } 
    $count = $stmt->rowCount();
} 
?>
<!DOCTYPE html>
<html lang="en">    
<head>
    <title>EpicOwl UK | CMS Users Edit Profile</title>
    <meta charset="utf-8">
    <link rel="shortcut icon" href="../images/favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" type="text/css" href="../css/main.css">
</head>
<body>
<div id="header">
    <a href="index.php"><img id="logo" src="../images/logo.png" /></a>
    <div id="navigation">
        <ul>
            <a href="../index.php"><li>Home</li></a>
            <a href="./profile.php"><li>My Profile</li></a>
            <a href="../admin/index.php"><li>Admin Panel</li></a>
        </ul>
    </div>
</div>
<div id="content">
<form method="post"><br />
    <h2>Edit Profile</h2>
    <label><strong>User Title:</strong></label><br />
    <input type="text" name="title" maxlength="50" placeholder="<?php echo ($userRow['title']); ?>" /><br /><br />
    <label><strong>My Location:</strong></label><br />
    <input type="text" name="location" maxlength="50" placeholder="<?php echo ($userRow['location']); ?>" /><br /><br />
    <label><strong>About Me:</strong><label><br />
    <textarea name="about" rows="13" cols="60" maxlength="255" placeholder="<?php echo ($userRow['about']); ?>"></textarea><br /><br />
    <button type="submit" name="update">Update</button><br /><br /><br />
    <?php
    if(isset($_POST['submit'])){
        header('refresh:20; Location: '.$_SERVER['REQUEST_URI']);
    }
    ?>
</form>
</div>
<div id="footer">
    <p class="copyright">&copy; EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Sauced Apples
  • 1,163
  • 2
  • 14
  • 37

3 Answers3

2

You are doing it wrong, you have to process the form submission BEFORE showing the HTML. PHP is being executed line-by-line so in your case you are firstly showing the data and then you are checking if the form is submitted. Simply move this code up where the rest of your PHP code is located (you can even remove the refresh stuff command):

if(isset($_POST['submit'])){
    header('Location: '.$_SERVER['REQUEST_URI']);
    die;
}

Edit:

People invented MVC because of cases like yours when you are mixing HTML and PHP and wonder why things don't work. Keep your PHP code at the top of the files, try not to write PHP code anywhere inside HTML, you will save yourself a lot of trouble. And also, use exit after calling header to stop code execution any further. Here is an updated version of your code, simplified and more "algorithmic" (I hope you do see and understand how the code flow goes):

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

include_once '../includes/conn.php';

if(!$user->is_loggedin()){
    $user->redirect('../users/login.php');
}

$id = $_SESSION['session'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id=:id");
$stmt->execute(array(":id"=>$id));

$userRow=$stmt->fetch(PDO::FETCH_ASSOC);

if (isset($_POST['submit'])) {
    $location = isset($_POST['location']) ? $_POST['location'] : null;
    $about = isset($_POST['about']) ? $_POST['about'] : null;
    $title = isset($_POST['title']) ? $_POST['title'] : null;

    $sql_part = array();
    $prepare = array();
    if ($location) {
        $sql_part[] = 'location = :location';
        $prepare[':location'] = $location;
    }
    if ($about) {
        $sql_part[] = 'about = :about';
        $prepare[':about'] = $about;
    }
    if ($title) {
        $sql_part[] = 'title = :title';
        $prepare[':title'] = $title;
    }
    $prepare[':id'] = $id;

    if (count($sql_part)) {
        $sql = 'UPDATE users SET ';
        $sql .= implode(', ', $sql_part);
        $sql .= ' WHERE id = :id';

        $stmt = $dbh->prepare($sql);

        if ($stmt) {
            // Find another way too pass these through the refresh
            // $result = $stmt->execute($prepare);
            // $count = $stmt->rowCount();
            header('Location: '. $_SERVER['REQUEST_URI']);
            exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">    
<head>
    <title>EpicOwl UK | CMS Users Edit Profile</title>
    <meta charset="utf-8">
    <link rel="shortcut icon" href="../images/favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" type="text/css" href="../css/main.css">
</head>
<body>
<div id="header">
    <a href="index.php"><img id="logo" src="../images/logo.png" /></a>
    <div id="navigation">
        <ul>
            <a href="../index.php"><li>Home</li></a>
            <a href="./profile.php"><li>My Profile</li></a>
            <a href="../admin/index.php"><li>Admin Panel</li></a>
        </ul>
    </div>
</div>
<div id="content">
<form method="post"><br />
    <h2>Edit Profile</h2>
    <label><strong>User Title:</strong></label><br />
    <input type="text" name="title" maxlength="50" placeholder="<?php echo ($userRow['title']); ?>" /><br /><br />
    <label><strong>My Location:</strong></label><br />
    <input type="text" name="location" maxlength="50" placeholder="<?php echo ($userRow['location']); ?>" /><br /><br />
    <label><strong>About Me:</strong><label><br />
    <textarea name="about" rows="13" cols="60" maxlength="255" placeholder="<?php echo ($userRow['about']); ?>"></textarea><br /><br />
    <button type="submit" name="update">Update</button><br /><br /><br />
</form>
</div>
<div id="footer">
    <p class="copyright">&copy; EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Avalanche
  • 1,468
  • 1
  • 11
  • 18
  • I get the same problem no matter where I put the above code. – Sauced Apples Jun 24 '15 at 19:18
  • Why don't you place all your update-related code inside the ```if``` checking whether the form was submitted? They need to be updated once the form was submitted anyways... – Avalanche Jun 24 '15 at 19:21
  • Great, now merge all three queries you have into one, so your code will get at least 3 times shorter. It is necessarily long and you have a lot of repeating code. – Avalanche Jun 24 '15 at 19:36
  • I appreciate the help but I'd rather get the refresh working then clean up. – Sauced Apples Jun 24 '15 at 19:37
  • How does your code look like at this point? Where did place the header? – Avalanche Jun 24 '15 at 19:45
  • It's the same as the question code, the edit was throwing variable problems and it worked before so I just want to get refresh working. – Sauced Apples Jun 24 '15 at 19:54
  • Everybody wants to get things working, but it is not that simple. You have to dig the problem deeper, this is what coding is about. You should work on that :) I have edited my answer by adding a fixed version of your code. It should works, I tested as far as I could. – Avalanche Jun 24 '15 at 21:04
  • I do see, thank you for your time. Although it does not update the database. – Sauced Apples Jun 25 '15 at 07:33
  • This is because I have commented by accident the line which executes the query along with the one counting rows :) ```// $result = $stmt->execute($prepare);``` – Avalanche Jun 25 '15 at 17:00
  • Hey. Yeah I had seen this, also `$stmt = $conn->prepare($sql);` was `$dbh` but this still does not update the database. Thanks – Sauced Apples Jun 25 '15 at 22:15
0

I managed to get the desired result by adding header('Location: ./editprofile.php'); after the database was updated. See bellow:

if($title!=''){
    $sql = "UPDATE users SET title=:title WHERE id=:id";    
    $stmt = $conn->prepare($sql); 
    if($stmt == false){ 
        $error = "User Title update failed. Please try again.";
    } 

    $result = $stmt->execute(array(":title"=>$title, ":id"=>$id));

    if($result == false) { 
        $error = "User Title update failed. Please try again.";
    } 
    $count = $stmt->rowCount();
} 

After:

if($title!=''){
    $sql = "UPDATE users SET title=:title WHERE id=:id";    
    $stmt = $conn->prepare($sql); 
    if($stmt == false){ 
        $error = "User Title update failed. Please try again.";
    } 

    $result = $stmt->execute(array(":title"=>$title, ":id"=>$id));

    if($result == false) { 
        $error = "User Title update failed. Please try again.";
    } 
    $count = $stmt->rowCount();
    header('Location: ./editprofile.php');  
} 
Sauced Apples
  • 1,163
  • 2
  • 14
  • 37
-1

just use JavaScript's-

window.location.reload().

In PHP you can use-

$page = $_SERVER['PHP_SELF'];
$sec = "10";
header("Refresh: $sec; url=$page");
Khairul Islam
  • 1,207
  • 1
  • 9
  • 20
  • Thanks for the suggestion, but I was looking for a better way to do it in PHP only. – Sauced Apples Jun 24 '15 at 19:21
  • @DanielMinett i just edited my answer. did you tried this way? – Khairul Islam Jun 24 '15 at 19:27
  • Using refresh in the header is not a very fancy solution. Far better choice is to use the built-in function [sleep](http://php.net/sleep), but it is still a solution I would not recomment. – Avalanche Jun 24 '15 at 19:29
  • Does not need to be fancy, just to work, this one didn't help. Inserted top of page. `if(isset($_POST['submit'])){ $page = $_SERVER['PHP_SELF']; $sec = "10"; header("Refresh: $sec; url=$page"); }` – Sauced Apples Jun 24 '15 at 19:34