Could someone help me with this code!!! So I'm trying to do a change user info part on my website, there's everything working except the change username part. In this part I have to check if the newUsername is not taken and then change it (if its not already taken), but when I launch my code it doesn't enter the (else if) statement after the (echo "username deja utiliser"). Can someone explain why it does that and give me a way to correct this problem
//change.php
$newUsername = $_POST['changeUsername'];
$newNom = $_POST['changeNom'];
$currentId = $_SESSION['id'];
$currentName = $_SESSION['name'];
//fonction that doesn't work
if(empty($newUsername)){
echo "username is empty";
}else if ($stmt = $con->prepare('SELECT username from users where USERNAME = ? ')) {
$stmt->bind_param('s', $newUsername);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($checkUsername);
$stmt->fetch();
if ($checkUsername === $newUsername) {
echo "username deja utiliser";
}else if($stmt = $con->prepare("UPDATE users SET USERNAME = '$newUsername' WHERE ID = ? ")){
$stmt->bind_param('s', $currentId);
$stmt->execute();
echo "les valeur on été modifier";
session_regenerate_id();
$_SESSION['name'] = $newUsername;
}else{
echo "les valeurs n'ont pas été modifier";
}
}
}
//function that works
if(empty($newNom)){
echo "nom is empty";
}else if($stmt = $con->prepare("UPDATE users SET NOM = '$newNom' WHERE ID = ? ")){
$stmt->bind_param('s', $currentId);
$stmt->execute();
echo "les valeur on été modifier";
}else{
echo "les valeurs n'ont pas été modifier";
}
//editProfile.php
<form action="change.php" method="POST">
<table>
<tr>
<td>Username:</td>
<td>
<label for="username"></label>
<input type="text" name="changeUsername" placeholder="<?php echo $_SESSION['name'] ?>" id="changeUsername">
</td>
</tr>
<tr>
<td>Nom:</td>
<td>
<label for="nom"></label>
<input type="text" name="changeNom" placeholder="<?php echo $nom ?>" id="changeNom">
</td>
</tr>
</table>
<input type="submit" value="modfier">
</form>
CodePudding user response:
Finally I found something that works. Is this code secure for SQL injection ?
//check if the username is taken
if(empty($newUsername)){
echo "username is empty";
}else if ($stmt = $con->prepare('SELECT username from users where USERNAME = ? ')) {
$stmt->bind_param('s', $newUsername);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($username);
$stmt->fetch();
if ($username === $newUsername) {
$checkUsername = true;
}
}
}
//change the username
if (empty($newUsername)) {
echo "username is empty";
} else if ($checkUsername != true) {
if ($stmt = $con->prepare("UPDATE users SET USERNAME = ? WHERE ID = ? ")) {
$stmt->bind_param('si', $newUsername, $currentId);
$stmt->execute();
echo "les valeur on été modifier";
session_regenerate_id();
$_SESSION['name'] = $newUsername;
} else {
echo "les valeurs n'ont pas été modifier";
}
} else {
echo "username deja utiliser ";
}