1
$check1 = mysqli_query($conn, "select * from Sailors where Name='$habboname'");
$check2 = mysqli_query($conn, "select * from Sailors where Position='$position'");
$num_rows = mysqli_num_rows($check1);
$num_rows2 = mysqli_num_rows($check2);
if ($num_rows > 0)  {
    echo "This user (<b>" . $habboname . "</b>) is already in our database.";
    exit();
} else {
    if ($num_row2 = 0){
    $sql =  "INSERT INTO Sailors (ID, Name, Joined, Rank, Billet, Position, Status, Promoter, Reason, Promo_Date)
    VALUES ('', '$habboname', '$date', '$rank', '$billet', '$position', 'Active', '$promoter', '$reason', '$date')";

    if ($conn->query($sql) === TRUE) {
        header("Location: useradded.php");
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
} else {
        echo $num_row2;
    }

It will always echo, even if the variable IS 0. I am really confused. If you know what the issue is, please let me know. Thanks :)

xkore2
  • 45
  • 3

4 Answers4

3

You are checking the assignment:

if ($num_row2 = 0){

While you should actually check for equality:

if ($num_row2 == 0){
Dekel
  • 60,707
  • 10
  • 101
  • 129
  • 1
    Ohhh! Thank you loads, I don't know how I missed that. – xkore2 Sep 01 '17 at 23:23
  • 1
    You are welcome :) Will appreciate if you mark the answer as correct when possible. – Dekel Sep 01 '17 at 23:24
  • 1
    I have to wait 15 minutes, will do. :) – xkore2 Sep 01 '17 at 23:28
  • 1
    When doing equality checks, it's better to use `===`. See [here](https://stackoverflow.com/questions/2063480/the-3-different-equals) – ishegg Sep 01 '17 at 23:42
  • 1
    @ishegg I agree when you don't know the type of the result, but that's not the case here since `mysqli_num_rows` will return the number of the results (0 if no results found). – Dekel Sep 01 '17 at 23:44
2
if ($num_row2 = 0){

is not comparison its actually assignment.

So Convert it to:-

if ($num_row2 == 0){ //comparison

Or

if ($num_row2 === 0){ //comparison
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
2
 if ($num_row2 = 0){

try to set $num_row2 = 0. Always it can. You can use this ways:

 if ($num_row2 == 0){

or expert way:

 if (!$num_row2){

Best regards.

Amin Djawadi
  • 25
  • 1
  • 6
1

One way you can avoid making an assignment error in PHP when your real intention is to do a comparison is to train yourself to code as follows:

if (0 == $num_row2)

It may be feel a little awkward at first, but it really can help in avoiding the assignment operator when one intends a comparison based on equality and of course the same technique is good for a comparison based on identity.

slevy1
  • 3,797
  • 2
  • 27
  • 33