Limit foreach loop to only one user? - php

I have a system where I want to limit the foreach to a designated user:
My output shows every date Enrolled, I could limit it to only one, but if I do, the single thing shown will be shown to every user as well.
This should only show one Enrolled Since and Not Enrolled Since, but I don't know if I should use an if statement or use a row query. I tried it but it only outputs error "Uncaught Error: Call to a member function result_array() on array in . . ."
(below is the code I tried to use row for, but outputs the said error above.)
<?php
$result_array = $res->result_array();
$results = array();
foreach ($res->result_array() as $row)
{
$results[] = $row;
}
?>
Here is my codes latest code called viewlogs.php
<?php
session_start();
if (!isset($_SESSION['username']))
{
header('location: login.php');
die();
}
?>
<?php
require"config.php";
require"sqlsrv.php";
$id=$_GET['id'];
$sql= 'SELECT * FROM students WHERE id= :id';
$stmt = $db-> prepare($sql);
$stmt->execute([':id' => $id ]);
$data= $stmt->fetch(PDO::FETCH_OBJ);
$query= 'SELECT EmployeeNo, FirstName, MiddleName, LastName, DateHired, ResignationDate FROM TA3.dbo.Employees';
$statement = $conn->query($query);
$statement->execute();
$res=$statement->fetchAll(PDO::FETCH_OBJ);
$q= 'SELECT TimeLogID, EmployeeID, RecordDate, RecordTime, Type, ActualTime FROM TA3.dbo.TimeLogs';
$st = $conn->query($q);
$st->execute();
$re=$st->fetchAll(PDO::FETCH_OBJ);
if (isset ($_POST['fname']) && (isset($_POST['lname']) && (isset($_POST['email']) && (isset($_POST['usn']) && (isset($_POST['schedule']) && (isset($_POST['year']) && (isset($_POST['strand']))))))))
{
$fname = $_POST['fname'];
$mname = $_POST['mname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$usn = $_POST['usn'];
$schedule = $_POST['schedule'];
$year = $_POST['year'];
$strand = $_POST['strand'];
}
if (isset ($_POST['DateHired']) && (isset($_POST['ResignationDate']) && (isset($_POST['EmployeeNo']))))
{
$DateHired = $_POST['DateHired'];
$ResignationDate = $_POST['ResignationDate'];
$EmployeeNo = $_POST['EmployeeNo'];
}
if (isset ($_POST['TimeLogID']) && (isset($_POST['EmployeeID']) && (isset($_POST['RecordDate']) && (isset($_POST['RecordTime']) && (isset($_POST['Type']) && (isset($_POST['ActualTime'])))))))
{
$TimeLogID = $_POST['TimeLogID'];
$EmployeeID = $_POST['EmployeeID'];
$RecordDate = $_POST['RecordDate'];
$RecordTime = $_POST['RecordTime'];
$Type = $_POST['Type'];
$ActualTime = $_POST['ActualTime'];
}
?>
<!DOCTYPE html>
<html>
<head>
<title>View Logs</title>
<link rel="icon" type="image/png" sizes="16x16" href="image/favicon-16x16.png">
<link rel="icon" type="image/png" sizes="32x32" href="image/favicon-32x32.png">
<meta name= "viewport" content="width= device-width, initial-scale=1">
<script defer src="js/fontawesome-all.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/viewlogs.css">
</head>
<body>
<div class="back"><a class="henny" href="students.php"><i class="fas fa-backward"></i> Back </a></div>
<div class="title"> <h1>Student Logs<span class="blink">_</span></h1></div>
<div class="grid">
<div class="student-info">
<label>First name</label>
<input value="<?= $data->fname; ?>" type="text" name="fname" readonly/>
<label>Middle name</label>
<input value="<?= $data->mname; ?>" type="text" name="mname" readonly/>
<label>Last name</label>
<input value="<?= $data->lname; ?>" type="text" name="lname" readonly/>
<label>USN</label>
<input value="<?= $data->usn; ?>" type="text" name="usn" readonly/>
<label>Strand</label>
<input value="<?= $data->strand; ?>" type="text" name="strand" readonly/>
<label>Schedule</label>
<input value="<?= $data->schedule; ?>" type="text" name="schedule" readonly/>
</div>
<div class="device-info">
<?php
$i = 0;
foreach ($res as $outcome): ?>
<label>Enrolled since</label>
<input value="<?= date('Y-m-d', strtotime($outcome->DateHired)); ?>" type="text" name="enrolled" readonly/>
<label>Not Enrolled since</label>
<input value="<?= $outcome->ResignationDate; ?>" type="text" name="notenrolled" readonly/>
<?php endforeach; ?>
</div>
<div class="logs">
<table style="width:100%" class="logs-table">
<tr>
<th style="width:25%">Date</th>
<th style="width:25%">Time</th>
<th style="width:12%">In</th>
<th style="width:12%">Break in </th>
<th style="width:12%">Break out</th>
<th style="width:12%">Out</th>
</tr>
</table>
</div>
</div>
<?php
$r = $db->prepare("SELECT * FROM students WHERE id LIKE :id");
$r->execute(array( ':id'=>'%'.$id. '%'));
if ($data=$r->fetch())
{
?>
<a class="print" target="_blank" href="print.php?id=<?= $data['id']; ?>"> Print <i class="fas fa-print"></i></a>
<?php
}
?>
</body>
</html>
and my sqlsrv.php
<?php
/*
Connection for sqlsrv
*/
try {
$conn = new PDO( 'sqlsrv:server=(localdb)\\v11.0;'
. 'AttachDBFileName=C:\\PROGRAMDATA\\TOUCHLINK TIME RECORDER 3\\TA3.mdf;Database=TA3');
$query = 'SELECT EmployeeNo, FirstName, MiddleName, LastName, DateHired FROM TA3.dbo.Employees ORDER BY EmployeeNo ASC';
$stmt = $conn->query($query);
$stmt->execute();
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>

IIUC - simply filter your query by the specific EmployeeNo (or whatever identifier of web user) by passing as a parameter the value returned from posted HTML form. This requires you to change code order where you run your query after assigning $_POST values.
...
if (isset ($_POST['DateHired']) && (isset($_POST['ResignationDate']) && (isset($_POST['EmployeeNo']))))
{
$DateHired = $_POST['DateHired'];
$ResignationDate = $_POST['ResignationDate'];
$EmployeeNo = $_POST['EmployeeNo'];
}
...
$query= 'SELECT EmployeeNo, FirstName, MiddleName, LastName, DateHired, ResignationDate
FROM TA3.dbo.Employees
WHERE EmployeeNo = ?';
$statement = $conn->prepare($query);
$statement->bind_param(1, $EmployeeNo);
$statement->execute();
$res = $statement->fetchAll(PDO::FETCH_OBJ);

Related

Unable to use $_SESSION in an other file (PHP)

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>

Admin page won't show

Warning: Cannot modify header information - headers already sent by
(output started at/admin/index.php:21) in
/var/www/web143366/html/admin/index.php on line 24
<?php
require_once('../config.php');
require_once('../php/functions.php');
?>
<!DOCTYPE>
<html lang="eng">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="admin.css">
<link rel="stylesheet" type="text/css" href="../layout.css">
</head>
<body>
<?php
if (!isset($_SESSION['adminid'])) {
header('Location: /admin/login');
} else {
?>
<div id="leftPanel">
<div class="przyciskPanelAdmina">Homepage</div>
<div class="przyciskPanelAdmina active">Dashboard</div>
<div class="przyciskPanelAdmina">Manage Accounts</div>
<div class="przyciskPanelAdmina">Add Account</div>
<div class="przyciskPanelAdmina">Add Category</div>
<div class="przyciskPanelAdmina">Messages</div>
<div class="przyciskPanelAdmina">Logout</div>
</div>
<div id="rightPanel">
<h3>Recent payments</h3>
<table>
<tr class='first'>
<td width='20%'>Account Login</td>
<td width='20%'>Account Password</td>
<td width='20%'>Date</td>
<td width='20%'>Amount</td>
<td width='20%'>Payment ID</td>
</tr>
<?php
$sql = $conn->prepare('SELECT accounts.login AS Login, accounts.password AS Pass, date, amount, paymentID FROM payments INNER JOIN accounts ON payments.accountId=accounts.id order by date DESC');
$sql->execute();
$result = $sql->get_result();
while ($row = $result->fetch_assoc()) {
echo "<tr><td width='20%'>" . $row['Login'] ."</td><td width='20%'>" . $row['Pass'] ."</td><td width='20%'>" . $row['date'] ."</td><td width='20%'>" . $row['amount'] ."$</td><td width='20%'>" . $row['paymentID'] ."</td></tr>";
}
?>
</table>
<div class="clear"></div>
</div>
<?php
}
?>
</body>
</html>
Edit all: This is the error. When I remove line 24 I get the following error.
Fatal error: Call to undefined method mysqli_stmt::get_result() in
/var/www/web143366/html/admin/login.php on line 32
Line 32: $result = $sql->get_result();
Code:
$sql = $conn->prepare('SELECT * FROM admin WHERE email = ?');
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>Wrong email or password</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$p = $row['password'];
$uid = $row['id'];
}
if (password_verify($pass, $p)) {
$_SESSION['adminid'] = $uid;
header('Location: /admin');
} else {
echo "<h1>Wrong email or password 2</h1>";
}
}
}
Login.php=
<?php
require_once('../config.php');
require_once('../php/functions.php');
?>
<!DOCTYPE>
<html lang="eng">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</head>
<body>
<?php
if (isset($_POST['loginBtn'])) {
$email = htmlspecialchars($_POST['mail']);
$pass = htmlspecialchars($_POST['password']);
$sql = $conn->prepare('SELECT * FROM admin WHERE email = ?');
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>Wrong email or password</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$p = $row['password'];
$uid = $row['id'];
}
if (password_verify($pass, $p)) {
$_SESSION['adminid'] = $uid;
header('Location: /admin');
} else {
echo "<h1>Wrong email or password 2</h1>";
}
}
}
if (isset($_POST['forgotBtn'])) {
$code = randomChars(20);
$email = htmlspecialchars($_POST['mail']);
$sql = $conn->prepare('SELECT * FROM admin WHERE email = ?');
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>No user with that email</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$uid = $row['id'];
}
$sql = $conn->prepare('INSERT INTO resetpass (userID, code) VALUES (?, ?)');
$sql->bind_param('ss', $uid, $code);
$sql->execute();
$message = "Your reset link: " . "http://" .$_SERVER['SERVER_NAME'] . '/admin/login?r=' . $code;
$to = $email;
$title = "Reset Password";
if (sendEmail($to, $message, $title)) {
echo "Email with reset code has been sent";
} else {
echo "Error while sending email";
}
}
}
if (isset($_POST['resetBtn'])) {
$nPass = htmlspecialchars($_POST['nPass']);
$code = $_POST['code'];
$password = password_hash($nPass, PASSWORD_DEFAULT);
$sql = $conn->prepare('SELECT * FROM resetpass WHERE code = ?');
$sql->bind_param('s', $code);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>Error</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$uid = $row['userID'];
}
$sql = $conn->prepare('UPDATE resetpass SET used = "1" WHERE code = ?');
$sql->bind_param('s', $code);
$sql->execute();
$sql = $conn->prepare('UPDATE admin SET password = ? WHERE id = ?');
$sql->bind_param('ss', $password, $uid);
$sql->execute();
echo "Password changed successfuly, you can now login";
}
}
?>
<?php
if (!isset($_SESSION['adminid'])) {
if (isset($_GET['forgot'])) { ?>
<form action="" method="POST">
<div class="formularzowyNaglowek">Account Email Address:</div>
<input type="email" name="mail" placeholder="Email address" required>
<input type="submit" name="forgotBtn" value="Reset">
</form>
<?php } else if (isset($_GET['r'])) { ?>
<form action="" method="POST">
<div class="formularzowyNaglowek">New Password:</div>
<input type="password" name="nPass" placeholder="New password" required>
<input type="hidden" name="code" value="<?php echo $_GET['r'] ?>" required>
<input type="submit" name="resetBtn" value="Reset">
</form>
<?php
} else { ?>
<h2 style="text-align: left;">Login to admin panel</h2>
<form action="" method="POST">
<div class="formularzowyNaglowek">Email Address:</div>
<input type="email" name="mail" placeholder="Email address" required>
<div class="formularzowyNaglowek">Password:</div>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" name="loginBtn" value="Login">
</form>
Forgot your password?
<?php
}
} else {
header('Location: /admin');
}
?>
</body>
</html>
The line header('Location: /admin/login'); will redirect to the login page when the user is not logged in.
The problem is, that the function header() doesnt work when there has been content outputted already (echo or html).
<?php
session_start(); // only if you havent called session_start in config.php or functions.php
require_once('../config.php');
require_once('../php/functions.php');
if (!isset($_SESSION['adminid'])) {
header('Location: /admin/login');
exit();
}
?>
<!DOCTYPE>
<html lang="eng">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="admin.css">
<link rel="stylesheet" type="text/css" href="../layout.css">
</head>
<body>
<div id="leftPanel">
<div class="przyciskPanelAdmina">Homepage</div>
<div class="przyciskPanelAdmina active">Dashboard</div>
<div class="przyciskPanelAdmina">Manage Accounts</div>
<div class="przyciskPanelAdmina">Add Account</div>
<div class="przyciskPanelAdmina">Add Category</div>
<div class="przyciskPanelAdmina">Messages</div>
<div class="przyciskPanelAdmina">Logout</div>
</div>
<div id="rightPanel">
<h3>Recent payments</h3>
<table>
<tr class='first'>
<td width='20%'>Account Login</td>
<td width='20%'>Account Password</td>
<td width='20%'>Date</td>
<td width='20%'>Amount</td>
<td width='20%'>Payment ID</td>
</tr>
<?php
$sql = $conn->prepare('SELECT accounts.login AS Login, accounts.password AS Pass, date, amount, paymentID FROM payments INNER JOIN accounts ON payments.accountId=accounts.id order by date DESC');
$sql->execute();
$result = $sql->get_result();
while ($row = $result->fetch_assoc()) {
echo "<tr><td width='20%'>" . $row['Login'] ."</td><td width='20%'>" . $row['Pass'] ."</td><td width='20%'>" . $row['date'] ."</td><td width='20%'>" . $row['amount'] ."$</td><td width='20%'>" . $row['paymentID'] ."</td></tr>";
}
?>
</table>
<div class="clear"></div>
</div>
</body>
</html>

After MySQL update display only updates after refresh [duplicate]

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

Refreshing page after sql update [duplicate]

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

Updating database with MYSQLi

I have been updating my members site so it will work with mysqli. I'm rather new to php and mysql.
I have a page where users can edit their information in a form which posts to send_post.php.
Can anyone tell me what is wrong with my code? I just get a white screen and a syntax error, 'unexpected ',' in send_post.php on line 7'.
This is the page with my form.
<?php
// See if they are a logged in member by checking Session data
include_once("php_includes/check_login_status.php");
if (isset($_SESSION['username'])) {
// Put stored session variables into local php variable
$username = $_SESSION['username'];
}
//Connect to the database through our include
include_once "php_includes/db_conx.php";
// Query member data from the database and ready it for display
$sql = "SELECT * FROM members WHERE username='$username' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// Now make sure that user exists in the table
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "That user does not exist or is not yet activated, press back";
exit();
}
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$state = $row["state"];
$city = $row["city"];
$name = $row["name"];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../assets/ico/favicon.png">
<title>Edit</title>
</head>
<body>
<br>
<div class = "container">
<div align="center">
<h3><br />
Edit your account info here<br />
<br />
</h3>
<table align="center" cellpadding="8" cellspacing="8">
<form action="send_post.php" method="post" enctype="multipart/form-data" name="form"
id="form">
<tr>
<td><div align="right">Name:</div></td>
<td><input name="city" type="text" id="city" value="<?php echo "$name"; ?>"
size="30" maxlength="24" /></td>
</tr>
<tr>
<td><div align="right">State:</div></td>
<td><input name="state" type="text" id="state" value="<?php echo "$state"; ?>"
size="30" maxlength="64" /></td>
</tr>
<tr>
<td><div align="right">City:</div></td>
<td><input name="city" type="text" id="city" value="<?php echo "$city"; ?>"
size="30" maxlength="24" /></td>
</tr>
<tr>
<td> </td>
<td><input name="Submit" type="submit" value="Submit Changes" /></td>
</tr>
</form>
</table>
</div>
</div>
</body>
</html>
This is the form processing page. send_post.php
<?php
if ($_POST['state']) {
$city = $_POST['city'];
$name = $_POST['name'];
//Connecting to sql db.
$connect = mysqli_connect("localhost","username","password","database");
$mysqli_query=($connect,"UPDATE members (`state`, `city`, `name` WHERE
username='$username'");
VALUES ('$state', '$city', '$name')";
mysqli_query($connect, $query);
mysqli_close($connect);
echo "Your information has been successfully added to the database.";
?>
Add a hidden field in the form like this
<input type="hidden" name="username" value="<?php echo $username; ?>">
Change send_post.php
<?php
//checking that all the fields have been entered
if( isset( $_POST['state'] ) && !empty( $_POST['state'] ) )
{
$state = $_POST['state'];
}
if( isset( $_POST['city'] ) && !empty( $_POST['city'] ) )
{
$city = $_POST['city'];
}
if( isset( $_POST['name'] ) && !empty( $_POST['name'] ) )
{
$name = $_POST['name'];
}
if( isset( $_POST['username'] ) && !empty( $_POST['username'] ) )
{
$username = $_POST['username'];
}
//Connecting to sql db.
$mysqli = new mysqli("localhost","username","password","database");
//updating database
$query = $mysqli->query( "UPDATE members SET `state` = '$state', `city` = '$city', `name` = '$name' WHERE `username` = '$username'" );
//closing mysqli connection
$mysqli->close;
//echoing that the information has been added
echo "Your information has been successfully added to the database.";
?>
change
$mysqli_query=($connect,"UPDATE members (`state`, `city`, `name` WHERE
username='$username'");
VALUES ('$state', '$city', '$name')";
to
$mysqli_query=($connect,"UPDATE members (`state`, `city`, `name`) VALUES ('$state', '$city', '$name') WHERE username='$username' ");

Categories