user1473757
user1473757

Reputation: 3

PHP IF Else Function Not Working

I have a problem, I can't get the result of my code. When I try to debug the code. I using IF statement in my code.

It's just simple, example : if kelas(based on user_id login) = 1, then redirect it to kelas1.php, if kelas = 2, the redirect to kelas 2, else no have a kelas.

Here it's my code :

<?php
session_start();

if(!isset($_SESSION['user_id'])) {      
    header('Location: form_login_siswa.html');
}
$user_id = $_SESSION['user_id'];
include ("config.php");
$query = "SELECT kelas FROM t_siswa WHERE user_id = '$user_id'";
$hasil = mysql_query($query);

while ($data = mysql_fetch_array($hasil)) {
    $kelas = $data['kelas'];

    if($kelas = 1) {
        include ("kelas1.php");
    }
    if($kelas = 2) {
        include ("kelas2.php");
    } else {
        echo "Tidak ada kelas";
    }
}
?>

Anyone, please help to solve the problem. Appreciated with your helps.

Thank you.

Upvotes: 0

Views: 564

Answers (6)

Razvan
Razvan

Reputation: 10093

Try using == instead of = . The "=" is an assignment operator and the expression gets the value of the right operand.

if($kelas == 1)
{
    include ("kelas1.php");
}
if($kelas == 2)
{
    include ("kelas2.php");
}
else
{
    echo "Tidak ada kelas";
}

Also, the statement will always echo "Tidak ada kelas"; if ($kelas == 1). Was this intentional?

Upvotes: 1

imnotquitejack
imnotquitejack

Reputation: 91

Take a look at the elsif structure.

while ($data = mysql_fetch_array($hasil)) {
  $kelas = $data['kelas'];

  if($kelas == 1) {
    include ("kelas1.php");
  } elseif($kelas == 2) {
    include ("kelas2.php");
  } else {
    echo "Tidak ada kelas";
  }
}

Or the switch structure:

while ($data = mysql_fetch_array($hasil)) {
  switch($data['kelas']){
    case 1:
      include ("kelas1.php");
      break;
    case 2:
      include ("kelas2.php");
      break;
    default:
    echo "Tidak ada kelas";
  }
}

Upvotes: 0

sikander
sikander

Reputation: 2286

You're missing an else and also not using the correct operator for comparison.

Also, switch around the comparison so that the first value is always a valid value.

if(1 == $kelas)
{
    include ("kelas1.php");
}
else if(2 == $kelas)
{
    include ("kelas2.php");
}
else
{
    echo "Tidak ada kelas";
}

Upvotes: 4

Matt Gibson
Matt Gibson

Reputation: 14949

if($kelas = 1)

should be

if($kelas == 1)

Upvotes: 1

Bruce
Bruce

Reputation: 1542

In your if statements using == for testing comparison rather than single = which is for assignment

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212402

$kelas = 1

is assignment

$kelas == 1

is comparison

Upvotes: 2

Related Questions