1

I'm trying to update a username record, with the new one that comes from form.

After I execute the statement, a record in my database is deleted but it is NOT REPLACED with a new one, that comes from form. I can not figure out why.

index.php:

<form action="change.php">
    <input type="text" name="txtNewUsername" id="txtNewUsername" placeholder="new username"><br/>
    <button>Change username</button>
</form>

change.php:

<?php
session_start();
require_once __DIR__.'/connect.php';

$txtNewUsername = $_POST['txtNewUsername'];
$sUsername = $_SESSION['txtUsername'];

try{
    $stmt = $db->prepare('UPDATE users SET username = :sNewUsername WHERE username = :sOldUsername');
    $stmt->bindValue('sNewUsername', $txtNewUsername);
    $stmt->bindValue(':sOldUsername', $sUsername);
    $stmt->execute();

    echo $txtNewUsername;


}catch(PDOEXception $ex){
    echo $ex;
}

I would like to replace the username of connected user with the one coming from a form.

  • This also assumes PHP sessions are always safe (which they are not) and unedited by external "virtual webhost users" see [How to prevent PHP sessions being shared between different apache vhosts? (answer off mine)](https://stackoverflow.com/questions/18262878/how-to-prevent-php-sessions-being-shared-between-different-apache-vhosts/18263063#18263063).. the SQL injection is not possible as you are using prepared statements as you should but it might be possible to change the username of a other user in some bad configuration cases if the session files are stored in one directory on the webserver – Raymond Nijland Jun 17 '19 at 13:21

2 Answers2

0
$stmt->bindValue('sNewUsername', $txtNewUsername);

I don't know if this is causing your problem but you are missing " : " sNewUsername

TOMBA
  • 205
  • 1
  • 11
0

The first thing I see is that you have no form method specified. Without a method=? the default is GET. Read about it here

You are trying to retrieve the updated value using POST

Change <form action="change.php"> to <form action="change.php" method="post">

With everything said... since using a get method is an easy hack, it is better to use post when passing information from one page to another.

You may also want to change <button>Change username</button> to <input type="button" name="submit" value="Change username" />

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Kuya
  • 7,280
  • 4
  • 19
  • 31