1


Right now my it shows that the username is available even when the name already exists in my database.

php

session_start();
$conne=mysqli_connect("localhost","username","","my_db");

$name = $_POST['name'];

$check_if_exists="SELECT * FROM names WHERE name = '$name'";
$count = mysql_num_rows($check_if_exists);
if($count != 0) { 

 $_SESSION['msg']="The name already exists. Please try another name";

} else {

$sql="INSERT INTO names(name) values('$name')";
if ($conn->query($sql) === TRUE) {
   $_SESSION['msg']="The name was inserted successfully";
  }
}

header("location:form.php");

Somehow it shows that the name is available and it will insert en give the message that the action was succesfull

html

<div class="msg"> 
  <?php if(isset($_SESSION['msg']))
{
    echo $_SESSION['msg'];
    unset($_SESSION['msg]);
}
?>
</div>

<form action="check_insert.php" method="post">

<input type="text" name="name" id="name" class="form-control" required> 
<input class="btn btn-default" type="submit" value="Voeg domein toe!">

</form>
Kevin
  • 63
  • 5
  • 1
    Maybe you are wrong on using mysql instead of mysqli – Alex Jan 01 '16 at 10:48
  • I can suggest you to fetch the result first, instead of counting them. if It had more than 0 items, it's successful and vice versa. It will effect your performance too – Alex Jan 01 '16 at 10:52
  • Why not just use the persons email address instead of a username - one less thing for them to forget – Ed Heal Jan 01 '16 at 11:12
  • Please Please Please and Pretty please look up SQL injection. – Ed Heal Jan 01 '16 at 11:23

2 Answers2

2

You have some issues in your code:

$check_if_exists="SELECT * FROM names WHERE name = '$name'";
$count = mysqli_num_rows($check_if_exists);

This should be like that (you miss the mysqli_query function):

$check_if_exists="SELECT * FROM names WHERE name = '$name'";
$result = mysqli_query($check_if_exists);
$count = mysqli_num_rows($result);
if($count != 0) { 
//your code
}

And this line:

if ($conn->query($sql) === TRUE) 
{
    $_SESSION['msg']="The name was inserted successfully";
}

Should be like that (you declared connection variable as $conne not $conn):

if ($conne->query($sql) === TRUE) 
{
    $_SESSION['msg']="The name was inserted successfully";
}

Side Note:

I don't think, if you not use name="submit" in button it will work or not.

devpro
  • 16,184
  • 3
  • 27
  • 38
1

In your code you just called mysqli_num_rows before calling mysqli_query. mysqli_num_rows counts the number of rows on a result set which is returned by mysqli_query and not on the query (text) itself.

Noor Ahmed
  • 1,507
  • 9
  • 14