在PHP上,我如何使用IF语句中的变量,并在IF语句之外使用它

I have a problem regarding my variable. I want to get my declared variable inside the IF statement and use it on the outside of my code. anyone can help me? this is my code that gives me error.

if(isset($_POST['search']))
{
     $_SESSION['find']=$_POST['search'];
     $search=$_SESSION['find'];
     echo "<b class='text-info'><u>".ucwords($search)."</u></b></b>";  
}

$query=mysql_query("select * from tbl_studentpersonalinfo where firstName LIKE '%".$search."%' OR lastName LIKE '%".$search."%'");
$total=mysql_num_rows($query);
$thevariableiwantoutside="";

  if(isset($_POST['search']))
  {
       $thevariableiwantoutside="what i want it to be";
       $_SESSION['find']=$_POST['search'];
       $search=$_SESSION['find'];
       echo "<b class='text-info'><u>".ucwords($search)."</u></b></b>";  
  }

$query=mysql_query("select * from tbl_studentpersonalinfo where firstName LIKE '%".$search."%' OR lastName LIKE '%".$search."%'");
$total=mysql_num_rows($query);

echo $thevariableiwantoutside;

You can't use a variable outside a if, if the variable is defined inside the if. This is the variables scope.

Solution :

  • Create the variable outside before the if
  • Fill it inside the if
  • Use it outside the if

Why dont you use $_POST['search'] itself?

 if(isset($_POST['search']))
{
     $_SESSION['find']=$_POST['search'];
     $search=$_SESSION['find'];
     echo "<b class='text-info'><u>".ucwords($search)."</u></b></b>";  
}

$query=mysql_query("select * from tbl_studentpersonalinfo where firstName LIKE '%".$_POST['search']."%' OR lastName LIKE '%".$_POST['search']."%'");
$total=mysql_num_rows($query);

just set:

$search=NULL;

before if statement, then you can use it.

I dont think right now you will get error if your IF statement is working fine. Even if you are getting it, then just add $search=""; before your if condition.