I have a PHP page with a HTML form and PHP on it. It asks the user to change their username and for it to change in the database. I have some code but it doesn't quite work and I'm stuck as to what I need. Could someone please give me some ideas?
HTML
<form id="edit" method="POST" action="">
<h1>
<label for="username">Username *</label>
<input id="username1" type="text" name="username1" value=""/>
</h1>
<h1>
<button id="submit" type="submit">Submit</button>
</h1>
</form>
PHP
<?php
if (isset($_POST['edit'])){
$username = $_POST["username1"];
$id = $_SESSION["user_id"];
$query = "UPDATE user SET username = '$username' WHERE id = '$id'";
}
?>
You have to ask for $_POST['username']
instead of $_POST['edit']
.
And your query must be executed by mysqli or PDO.
<?php
if (isset($_POST['username1'])){
$username = $_POST["username1"];
$id = $_SESSION["user_id"];
$query = "UPDATE user SET username = '$username' WHERE id = '$id'";
mysqli_query($database_con, $query);
}
?>
But these method is unsecure, because $username and $id could contain SQL-Injection.
Use prepared statements instead.
<?php
$con = new mysqli("host", "user", "password", "databasename");
if (isset($_POST['username1'])){
$username = $_POST["username1"];
$id = $_SESSION["user_id"];
$stmt = $con->prepare("UPDATE user SET username = ? WHERE id = ?");
$stmt->bind_param("si",$username,$id);
$stmt->execute();
}
?>