0

I am starting to get the hang of web development. I am facing a minor problem which is the following: Undefined index: username

I know it is because of the fact that I am using GET but the actual php script works and changes ARE MADE to the db - which is good. What is not good is the fact that this error is being displayed to the user: Undefined index: username

This is my code:

<!doctype html>
    <form id='register' action='changeticket.php' method='POST'>
    <input type="hidden" name="username" value="<?php echo $_GET['username']; ?>" >
    <fieldset >
    <legend>Change ticket</legend>
    <label for='ticket' >Proposed ticket request number: </label>
    <input type='text' name='ticketValue' id='tickets'  />
    <input type='submit' name='Submit' value='Submit' />
    </fieldset>
</form>
<?php
require "init.php";

if(!empty($_POST['ticketValue']) && !empty($_POST['username'])){
    $ticketValue = $_POST['ticketValue'];
    $stmt = "UPDATE ticketTable SET ticket = ? WHERE username = ?";
    $result = $dbcon->prepare($stmt);
    $result->bind_param('ss', $ticketValue, $username);
    $result->execute();
    echo "Ticket has been changed";
} 
else{
    echo "Not able to make changes sorry";
}
?>

I don't want to make the parameters visible in the url after i click submit so I am using POST. Like I said it works, but the error Undefined index: username is being displayed.

How can I fix this?

Thanking you

3 Answers3

3

One option is to use $_REQUEST instead of $_GET. $_REQUEST has both variables ( $_GET and $_POST)

0

You forgot to initialize $username..

    <!doctype html>
    <form id='register' action='changeticket.php' method='POST'>
    <input type="hidden" name="username" value="<?php echo $_GET['username']; ?>" >
    <fieldset >
    <legend>Change ticket</legend>
    <label for='ticket' >Proposed ticket request number: </label>
    <input type='text' name='ticketValue' id='tickets'  />
    <input type='submit' name='Submit' value='Submit' />
    </fieldset>
</form>
<?php
require "init.php";

if(!empty($_POST['ticketValue']) && !empty($_POST['username'])){
    $ticketValue = $_POST['ticketValue'];
    $username = $_POST['username'];
    $stmt = "UPDATE ticketTable SET ticket = ? WHERE username = ?";
    $result = $dbcon->prepare($stmt);
    $result->bind_param('ss', $ticketValue, $username);
    $result->execute();
    echo "Ticket has been changed";
} 
else{
    echo "Not able to make changes sorry";
}
?>
Aamir
  • 326
  • 2
  • 8
-2

Since you are using POST method instead of GET method to send the parameters, then you should change the following part:

<input type="hidden" name="username" value="<?php echo $_GET['username']; ?>" >

To:

<input type="hidden" name="username" value="<?php echo $_POST['username']; ?>" >
skangmy
  • 117
  • 1
  • 3
  • 10