PHP-Variable scope

时间:2015-07-31 20:52:42

标签: php scope

i hope u can help me.

 <html>
    <head>
    </head>
    <body>
    <?php
        $ime=$_POST["p_ime"];
        $grad="";
        $connection1=mysql_connect("localhost","Admin","rentacar") or die(mysql_error);
        mysql_select_db("test",$connection1) or die(mysql_error);
        $selectQuery="SELECT idgrad, naziv from grad";
        $result=mysql_query($selectQuery,$connection1) or die ("Ne funkcionise");
        while($row=mysql_fetch_array($result))
        {
            //echo $row["naziv"];
            //echo $row["idgrad"];
            if($_POST["p_grad"]==$row["naziv"]){
            $grad=$row["idgrad"];
            }
            echo $grad;
        }
        if ($grad="")
            header("Location:formaGrad.html");
        if ($ime!="" || $grad!=""){
        echo $ime;
        echo $grad;
        $connection2=mysql_connect("localhost","Admin","rentacar") or die(mysql_error);
        mysql_select_db("test",$connection2) or die(mysql_error);
        $insertQuery="INSERT INTO korisnik VALUES
                    (NULL,"."\"".$ime."\","."\"".$grad."\")";
        mysql_query($insertQuery,$connection2);
        echo " Uspiješno unešen grad $ime";
        }
        else{
            echo "<br><br><h1 align=\"center\">Nisu unešeni zahtjevani podaci</h1>";
        }
        ?>
    </body> 
    </html>

In this code i have problem with variable $grad. As u can see. If everything is fine. It should print out.

  1. echo $grad from while loop. wich works fine.
  2. echo $ime in 1st "if" also works fine.
  3. echo $grad in 1st "if" well, that doesn't work, it simply dont print anything.
  4. echo " Uspiješno unešen grad $ime"; in line 31. also works fine

So it print out $grad inside while loop but dont outside so i guess i have scope problem, but i dont know how to solve it. Please help.

1 个答案:

答案 0 :(得分:1)

This part of your code is the problem

if ($grad="")
        header("Location:formaGrad.html");

it should be

if ( $grad == "")...

Cheers.