Amoro Amoro - 2 months ago 11
MySQL Question

Optional Field Update Query

I have a small form connected to an optional field in my database. it is not required in any way.

if you visit the page on there is nothing in the input field it gives me a $gamername undefined. also when visiting the page it automatically shows the echo statement of "GameName Updated" when i haven't even click the form button. if i put something in the form it will up date it to the db as it should.. but it also wont echo the field unless i refresh the page but then it submits it all over again.

<?php

if(isset($_SESSION['uid'])) {
$user_id = $_SESSION['uid'];

$sql = "SELECT * FROM users WHERE uid = '{$user_id}' ";
$result = query($sql);

while (($row = mysqli_fetch_assoc($result)) != false) {

$user_id = $row['uid'];
$gamename = $row['gamename'];

}
}

?>
<?php

function update_game_name(){

$user_id = $_SESSION['uid'];
$gamename = escape($_POST['gamename']);

$sql ="UPDATE users SET gamename='$gamename' WHERE uid='$user_id'";
$result = query($sql);

echo ('GameName Updated.');



}
?>
<div class="container no-scope-wrap">
<div class="row">
<div class="col-md-12">
<?php update_game_name(); ?>
<div class="no-scope-border">
<h2 class="form-field-title">Game Name</h2>
<form role="form" action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<div class="form-group">
<label class="form-field-label">GameName</label>
<input class="form-control input-lg" id="name" name="gamename" type="text" placeholder="GameName" value="<?php echo $gamename;?>">
</div>
<button type="submit" name="update_game_name" id="btn" class="btn btn-default btn-lg">Update GameName</button>
</form>
</div>
</div>
</div>
</div>

Answer

In your function, you need to check if there is post data after making the update:

  function update_game_name(){

    if ($_SERVER["REQUEST_METHOD"]!="POST") return;

    $user_id = $_SESSION['uid'];           
    $gamename = escape($_POST['gamename']);        

    $sql ="UPDATE users SET gamename='$gamename' WHERE uid='$user_id'"; 
    $result = query($sql);

    echo ('GameName Updated.');



  }

Note that this function is called every time you load the page. The warning message is shown because the function was called without post data.