I want to display the error if user entered a duplicate name. But, it's not working. It keeps the name inserted even it's same. So, here is my code :
$namaErr = "";
$error==false;
if (isset($_POST['btnSubmit'])) {
if(isset ($_POST['nama'])){
$nama = $_POST['nama'];
$query ='SELECT nama FROM daftar_pengguna WHERE nama="' . $nama . '" LIMIT
1';
$result = mysqli_query($query);
$totalNumRowResult = mysqli_num_rows($result);
if($totalNumRowResult > 0){
$error=true;
$namaErr="Nama ini telah digunakan!!";
}
}
If no error, it will inserted in database :
else{
$query="INSERT INTO daftar_pengguna(nama) VALUES
('$nama')";
$res = mysqli_query($query);
header('Location:index.php?registered=true');
}
}
I've searched all question like mine but, no luck.
I suggest two things:
Merge the if conditions to one block , this will remove the braces confusion had as I noted in above comment and also noted by Sujith.
Also I suggest you sanitize the $_POST variable before sending to Database query...
See code below with the suggested modifications:
<?php
$namaErr = "";
$error = false;
# Merge condition checks in One block using && (AND)
if (isset($_POST['btnSubmit']) && isset($_POST['nama'])) {
$nama = $_POST['nama'];
# Sanitize the input before running into Database query
$nama = filter_var($nama, FILTER_SANITIZE_STRING);
$query ='SELECT nama FROM daftar_pengguna WHERE nama="' . $nama . '" LIMIT
1';
$result = mysql_query($query);
$totalNumRowResult = mysql_num_rows($result);
if($totalNumRowResult > 0){
$error=true;
$namaErr="Nama ini telah digunakan!!";
}
else{
$query="INSERT INTO daftar_pengguna(nama) VALUES ('$nama')";
$res = mysql_query($query);
header('Location:index.php?registered=true');
}
}
There was a problem with ther braces. This should work
$namaErr = "";
$error==false;
if (isset($_POST['btnSubmit'])) {
if(isset ($_POST['nama'])){
$nama = $_POST['nama'];
$query ='SELECT nama FROM daftar_pengguna WHERE nama="' .$nama . '" LIMIT 1';
$result = mysql_query($query);
$totalNumRowResult = mysql_num_rows($result);
if($totalNumRowResult > 0){
$error=true;
$namaErr="Nama ini telah digunakan!!";
}
else{
$query="INSERT INTO daftar_pengguna(nama) VALUES
('$nama')";
$res = mysql_query($query);
header('Location:index.php?registered=true');
}
}
}
try with this query :
$query ='SELECT nama FROM daftar_pengguna WHERE nama="' . $nama . '" ';