I am trying to creat a crud application using PHP, I have succeeded to display my data table from postgres but when i try i got some errors. this is my code :
<?php require 'database.php'; $id = null; if ( !empty($_GET['Code_Espece'])) { $id = $_REQUEST['Code_Espece']; } if ( null==$id ) { header("Location: index.php"); } if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_POST)) {
$firstnameError = null;
if (isset($_POST['Nom_Scien'])) {
$firstname = $_POST['Nom_Scien'];
}
$valid = true;if (empty($firstname)) { $firstnameError = 'Please enter firstname'; $valid = false; }
if ($valid) { $pdo = Database::connect(); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'UPDATE espece SET Nom_Scien = ? WHERE Code_Espece = ?';
$q = $pdo->prepare($sql);
$q->execute(array($firstname));
Database::disconnect();
header("Location: index.php");
}
}else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT * FROM espece where "Code_Espece" = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$firstname = $data['Nom_Scien'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Crud-Update</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
</div>
<form method="post" action="update.php?Code_Espece=<?php echo $id ;?>">
</div>
<div class="control-group<?php echo!empty($firstnameError) ? 'error' : ''; ?>">
<label class="control-label">Nom Scientifique</label>
<br />
<div class="controls">
<input type="text" name="nomscientifique" value="<?php echo!empty($firstname) ? $firstname : ''; ?>">
<?php if (!empty($firstnameError)): ?>
<span class="help-inline"><?php echo $firstnameError; ?></span>
<?php endif; ?>
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-success" name="update" value="update">
<a class="btn" href="index.php">Retour</a>
</div>
</form>
</div>
</body>
</html>
The problem is when i put what i want to change and click in the button 'Update' it return the following message : 'Please enter firstname' inspite of teh input isnot empty.
Thank you ;
Change <input type="text" name="nomscientifique" value="<?php echo!empty($firstname) ? $firstname : ''; ?>"> to <input type="text" name="Nom_Scien" value="<?php echo!empty($firstname) ? $firstname : ''; ?>">
Related
This question already has answers here:
How to redirect to the same page in PHP
(9 answers)
Closed 8 months ago.
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">
<img id="logo" src="../images/logo.png" />
<div id="navigation">
<ul>
<li>Home</li>
<li>My Profile</li>
<li>Admin Panel</li>
</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">© EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
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">
<img id="logo" src="../images/logo.png" />
<div id="navigation">
<ul>
<li>Home</li>
<li>My Profile</li>
<li>Admin Panel</li>
</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">© EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
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');
}
just use JavaScript's-
window.location.reload().
In PHP you can use-
$page = $_SERVER['PHP_SELF'];
$sec = "10";
header("Refresh: $sec; url=$page");
Hello good afternoon, I'm having the trouble of not being able to use add a $_POST value to my $_SESSION variable so that I can use it later in my profile file.
I can give it other values like "hello" outside the if and it echoes hello in levraiprofilewesh.php.
I've tried making $_SESSION a super global variable and global but it didn't work.
I've been stuck on it for a few hours :(.
I don't need to upload the website on the web, it's just for local use, so there's no need for privacy feedback although it has helped me for the future.
login.php code:
<?php
session_start();
include("db_connect.php");
if(isset($_POST['login_button'])) {
$user_email = trim($_POST['user_email']);
$user_password = trim($_POST['password']);
$_SESSION['password'] = $user_password;
$usql = "SELECT * FROM users WHERE Email='$user_email' && Password='$user_password'";
$uresult = mysqli_query($db, $usql) or die("database error:". mysqli_error($db));
$urow = mysqli_fetch_assoc($uresult);
//while($row = mysqli_fetch_array($uresult))
//$STPMARCHEFRERE = $row['Firstname'];
//$SESSION = $row['Firstname'];
if($urow['Password']==$user_password){
setcookie("userid",$user_password,time()+(60*60*24*7));
setcookie("useremail",$user_email,time()+(60*60*24*7));
//$GLOBALS['SESSION'] = $user_password;
$time=time();
$queryz = "UPDATE Users
Set Online='Online',
Time='$time'
WHERE Password='$user_password' ";
$db->query($queryz) or die('Errorr, query failed to upload');
echo "ok";
} else {
echo "email or password does not exist."; // wrong details
}
}
?>
levraiprofilewesh.php code:
<?php
session_start();
include("login.php");
$connection = mysqli_connect('localhost', 'root','','phpchart');
if(isset($_SESSION['password'])) {
$username = $_SESSION['password'];
$query = "SELECT *
FROM users
WHERE Password = '%$username%'";
$select_user_profile_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($select_user_profile_query)) {
$post_tamere = $row['Firstname'];
$post_tondaron = $row['Sirname'];
$post_tasoeur = $row['Phone'];
$post_tonneveu = $row['Institution'];
$post_julia = $row['Email'];
}
}
?>
<?php
if(isset($_POST['edit_user'])) {
$user_firstname = $_POST['user_firstname'];
$user_lastname = $_POST['user_lastname'];
$user_role = $_POST['user_role'];
//$post_image = $_FILES['image']['name'];
//$post_image_temp = $_FILES['image']['tmp_name'];
$username = $_POST['username'];
$user_email = $_POST['user_email'];
$user_password = $_POST['user_password'];
//$post_date = date('d-m-y');
//move_uploaded_file($post_image_temp, "./images/$post_image" );
$query = "SELECT randSalt FROM users";
$select_randsalt_query = mysqli_query($connection, $query);
if(!$select_randsalt_query) {
die("Query Failed" . mysqli_error($connection));
}
$row = mysqli_fetch_array($select_randsalt_query);
$salt = $row['randSalt'];
$hashed_password = crypt($user_password, $salt);
$query = "UPDATE users SET ";
$query .="user_firstname = '{$user_firstname}', ";
$query .="user_lastname = '{$user_lastname}', ";
$query .="user_role = '{$user_role}', ";
$query .="username = '{$username}', ";
$query .="user_email = '{$user_email}', ";
$query .="user_password = '{$hashed_password}' ";
$query .= "WHERE username = '{$username}' ";
$edit_user_query = mysqli_query($connection,$query);
confirmQuery($edit_user_query);
}
?>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<div id="wrapper">
<!-- Navigation -->
<div id="page-wrapper">
<div class="container-fluid">
<!-- Page Heading -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Welcome to Profile
<small>Author</small>
</h1>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Firstname</label>
<input type="text" value="<?php echo $post_tamere; ?>" class="form-control" name="user_firstname">
</div>
<div class="form-group">
<label for="post_status">Lastname</label>
<input type="text" value="<?php echo $post_tondaron; ?>" class="form-control" name="user_lastname">
</div>
<div class="form-group">
<select name="user_role" id="">
<option value="subscriber"><?php echo $user_role; ?></option>
<?php
if($user_role == 'admin') {
echo "<option value='subscriber'>subscriber</option>";
} else {
echo "<option value='admin'>admin</option>";
}
?>
</select>
</div>
<!--<div class="form-group">
<label for="post_image">Post Image</label>
<input type="file" name="image">
</div>-->
<div class="form-group">
<label for="post_tags">Phone</label>
<input type="text" value="<?php echo $post_tasoeur; ?>" class="form-control" name="username">
</div>
<div class="form-group">
<label for="post_content">Email</label>
<input type="email" value="<?php echo $post_tonneveu; ?>" class="form-control" name="user_email">
</div>
<div class="form-group">
<label for="post_content">Password</label>
<input type="password" value="<?php echo $post_julia; ?>" class="form-control" name="user_password">
</div>
<h1><?php echo $_SESSION['superhero']; ?></h1>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="edit_user" value="Update Profile">
</div>
</form>
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
I have an HTML login form whose action sends to another PHP file where there is a function that is supposed to login user on to the site. When submited form leads to that php file but it shows an empty page like it doesn't trigger that function. I put echo and die on top of the function but still, nothing happens.
Also when I echo something outside of function it displays what I entered in echo, so it calls the right file just it won't load function. Any help is appreciated. Here is my code.
login.php
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (isset($_POST["submit"])) {
login_function();
}
}
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/login_assets/css/style.css">
<link href="https://fonts.googleapis.com/css?family=Raleway:300,400,500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/login_assets/css/media.css">
<script src="/login_assets/js/jquery.min.js"></script>
<script src="/login_assets/js/modernizr.custom.js"></script>
</head>
<body>
<header class="clear hBlack">
<div class="jLogo"><img src="/login_assets/images/logo.png" alt=""></div>
</header>
<div class="logArea clear">
<form action="custom_functions.php" method="post" enctype="application/x-www-form-urlencoded">
<div class="logbox">
<div class="box clear">
<h2>Members Area</h2>
<div class="logTypes">
<input type="text" name="username" class="logtextbox" placeholder="Username or email">
<span class="text-danger"><?php echo $username_error; ?></span>
<input type="password" name="password" class="logtextbox" placeholder="Password"><br>
<span class="text-danger"><?php echo $password_error; ?></span>
<!-- <input type="text" name="captcha" class="logtextbox" placeholder="Enter the code shown below"><br>
<img style="margin: 0 auto;" src="captcha.php">
<span class="text-danger"><?php echo $captcha_error; ?></span> -->
<div style="text-align: center">Remember my login: <input name="remember" type="checkbox"></div>
</div>
</div>
<input type="submit" value="submit" class="logBtn" name="submit"/>
</div>
</form>
</div>
<footer class="clear">
<p class="fNav">Home<span>|</span>
Log Out
</p>
</footer>
</body>
</html>
custom_functions.php
<?php
//echo "AAAAAAAAA";
function validation($form_data)
{
$form_data = trim(stripcslashes(htmlspecialchars($form_data)) );
return $form_data;
}
function login_function() {
//echo "AAAAAAAAAA";
//die('!');
session_start();
require 'connection.php';
$username_error = "";
$password_error = "";
//$captcha_error = "";
$v_username = $_POST['username'];
$v_password = $_POST['password'];
//$v_captcha = $_POST['captcha'];
$username = validation($v_username);
$password = validation($v_password);
//$captcha = validation($v_captcha);
$remember = isset($_POST['remember']);
if (empty($username)) {
$username_error = "<p>Please enter your username!</p>";
}
if (empty($password)) {
$password_error = "<p>Please enter your password!</p>";
}
if (!empty($username) && !empty($password)) {
$sql = "SELECT * FROM member_auth WHERE username = :username";
//$sql = "SELECT * FROM member_auth LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$cryptpass = $user['cryptpass'];
if($user === false){
$username_error = "<p>User doesn't exist</p>";
} elseif ($user) {
$newPass = crypt($password, $cryptpass);
if ($cryptpass == $newPass) {
$_SESSION['loggedin'] = TRUE;
$_SESSION['username'] = $username;
if ($remember == "on") {
setcookie("remember", $username, time()+3600);
}
header('Location: login_success.php');
} else {
$password_error = "<p>Password is not correct!</p>";
}
}
}
}
?>
Move your condition from same page to custom_functions.php
if ($_SERVER['REQUEST_METHOD'] == "POST"){
if(isset($_POST["submit"])) {
login_function();
}
}
or
<form action="" method="post" enctype="application/x-www-form-urlencoded">
you call login function in the login page and define the function in custom.php page so it does not find any function in this file put your code in the same function and it will work.
if ($_SERVER['REQUEST_METHOD'] == "POST"){
if(isset($_POST["submit"])) {
login_function();
}}
This question already has answers here:
How to redirect to the same page in PHP
(9 answers)
Closed 8 months ago.
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">
<img id="logo" src="../images/logo.png" />
<div id="navigation">
<ul>
<li>Home</li>
<li>My Profile</li>
<li>Admin Panel</li>
</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">© EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
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">
<img id="logo" src="../images/logo.png" />
<div id="navigation">
<ul>
<li>Home</li>
<li>My Profile</li>
<li>Admin Panel</li>
</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">© EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
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');
}
just use JavaScript's-
window.location.reload().
In PHP you can use-
$page = $_SERVER['PHP_SELF'];
$sec = "10";
header("Refresh: $sec; url=$page");
This question already has answers here:
How to redirect to the same page in PHP
(9 answers)
Closed 8 months ago.
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">
<img id="logo" src="../images/logo.png" />
<div id="navigation">
<ul>
<li>Home</li>
<li>My Profile</li>
<li>Admin Panel</li>
</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">© EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
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">
<img id="logo" src="../images/logo.png" />
<div id="navigation">
<ul>
<li>Home</li>
<li>My Profile</li>
<li>Admin Panel</li>
</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">© EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
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');
}
just use JavaScript's-
window.location.reload().
In PHP you can use-
$page = $_SERVER['PHP_SELF'];
$sec = "10";
header("Refresh: $sec; url=$page");