Is there anyway to assign/change a PHP variable after the page has loaded? For example, let's say I have the variable $username
. $username
is not set yet, but it will be set once the user has submitted a form with an input field that will set $username
. So essentially, $username
will become $username = $_POST["username"];
Let's say the user decides to change the username again. (Note: the page never refreshes upon user submission, it is the same page.) $username gets assigned to $_POST["username"] again. With this current methodology, it is not working for me. I have constructed the following:
$prevUsername;
$newUsername;
if ((isset($_POST["username"]))
{
$newUsername = $_POST["username"];
if ($username == "")
{
$db->query("INSERT INTO Users (`username`) VALUES ('$newUsername')");
$prevUsername = $newUsername;
}
else
{
$db->query("UPDATE Users SET username = '$newUsername' WHERE username = '$prevUsername'");
$prevUsername = $newUsername;
}
}
When the user submits a username, it works properly. It only stops working properly when the user wants to update their username. Updating their username does not return any errors, but it does not update based on their previous username. Instead of updating, it stays the same as if the UPDATE SQL statement never initiated. Is there a way to fix this problem?
With Session variables:
session_start();
ob_start();
$_SESSION["username"];
if (isset($_POST["username"]))
{
if (isset($_SESSION["username"]))
{
$db->query("UPDATE Users SET username = '{$_POST['username']}' WHERE username = '{$_SESSION['username']}'");
}
else
{
$db->query("INSERT INTO Users (`username`) VALUES ('{$_POST['username']}')");
$_SESSION["username"] = $_POST["username"];
}
}
PHP is stateless
, this means nothing is stored in the servers memory after the request is done. In other words, PHP is not capeable of keeping track of the var $prevUsername
, because it get lost between request. What you should do is store the variables in something that is more persistent, e.g. sessions :
<?php
session_start();
if (isset($_POST['username'])) {
if (!isset($_SESSION['prevUsername'])) {
$stmt = $db->prepare('INSERT INTO Users (`username`) VALUES (?)');
$stmt->bind_param('s', $_POST['username'])
$stmt->execute();
$_SESSION['prevUsername'] = $_POST['username'];
}else{
$stmt = $db->prepare('UPDATE Users SET username = ? WHERE username = ?');
$stmt->bind_param('s', $_POST['username'])
$stmt->bind_param('s', $_SESSION['prevUsername'])
$_SESSION['prevUsername'] = $_POST['username'];
}
}
And if you want to use it with ajax:
<html>
<head>
<meta charset="UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<form method="POST">
<input type="text" id="txt_username" />
<input type="submit" id="btn_submit" />
</form>
<hr />
<div id="username"></div>
<div id="output"></div>
<hr />
<script>
$(function() {
$('#btn_submit').on('click', function(e) {
e.preventDefault();
request();
});
request();
});
function request() {
$.ajax({
type: 'POST',
url: 'http://www.darkbee.be/stack/username/process.php',
data: {'username':$('#txt_username').val(),},
dataType:'json',
success: function(e) {
$('#username').html('Current username:'+e.current_username);
$('#output').html('Action:'+e.message);
},
});
}
</script>
</body>
</html>
process.php
<?php
session_start();
$output = array(
'current_username' => '',
'message' => '',
);
if (isset($_POST['username']) && trim($_POST['username']) != '') {
if (!isset($_SESSION['prevUsername'])) {
/*
$stmt = $db->prepare('INSERT INTO Users (`username`) VALUES (?)');
$stmt->bind_param('s', $_POST['username'])
$stmt->execute();
*/
$output['message'] = 'Tracked new username: '.$_POST['username'];
$_SESSION['prevUsername'] = $_POST['username'];
}else{
/*
$stmt = $db->query('UPDATE Users SET username = ? WHERE username = ?');
$stmt->bind_param('s', $_POST['username'])
$stmt->bind_param('s', $_SESSION['prevUsername'])
*/
$output['message'] = 'Changed old username from '.$_SESSION['prevUsername']. ' to '.$_POST['username'];
$_SESSION['prevUsername'] = $_POST['username'];
}
}else{
$output['message'] = 'Nothing happend';
}
if (isset($_SESSION['prevUsername'])) $output['current_username'] = $_SESSION['prevUsername'];
header('Content-Type: application/json');
echo json_encode($output);