其他块中的PHP代码不会回显变量

时间:2012-05-31 23:24:53

标签: php html

我有以下用于创建网站的代码:

    <?php
    session_start();
        ?>
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org   /TR/xhtml11          /DTD/xhtml11.dtd">
         <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
<?php
require_once("connect.php");
                if(isset($_POST["firstName"]))
                {
                    $fname = mysql_real_escape_string($_POST["firstName"]);
                    $lname = mysql_real_escape_string($_POST["lastName"]);
                    $email = mysql_real_escape_string($_POST["email"]);
                    $pass = mysql_real_escape_string($_POST["password"]);
                    $cpass = mysql_real_escape_string($_POST["cPassword"]);

                    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
                    $salt = "";
                    for($i = 0; $i < 30; $i++)
                    {
                        $rand = rand(0,35);
                        $salt = $salt . substr($chars, $rand, 1);
                    }
                    $hash = crypt($salt . $pass);
                    $query = "INSERT INTO users (salt, hash, email, fname, lname) VALUES ('$salt', '$hash', '$email', '$fname', '$lname')";
                    $result = mysql_query($query);
                    $cString = "";
                    for($i = 0; $i < 30; $i++)
                    {
                        $rand = rand(0, 35);
                        $cString = $cString . substr($chars, $rand, 1); 
                    }

                }
        ?>
        <link rel="stylesheet" type="text/css" href="styles/common.css"/>
        <link rel="stylesheet" type="text/css" href="styles/thanks.css"/>
    </head>

    <body>
        <?php
            echo $cString;  
        ?>

为什么我的页面上没有显示$cString的值?如果我回显它显示的字符串,但是当我回显变量时它没有显示。这是为什么?

4 个答案:

答案 0 :(得分:1)

$cString的值仅在定义$_POST["firstName"]时设置。

顺便说一下,你可以使用字符串解除引用而不是substr,所以代替:

$cString = $cString . substr($chars, $rand, 1);

你可以这样做:

$cString = $cString . $chars[$rand];

答案 1 :(得分:0)

$ cString未在同一范围内设置。鉴于此代码,如果你把

$cString = "";

在require_once行之后,它应该可以工作。

<强>更新

您很可能无法显示完整代码,$cString是在函数内构建的。在函数内声明的变量在外部不可用。一些选择:

  1. 当函数结束时返回$cString

    function my_fn()
    {
        $cString = 'abc';
        return $cString;
    }
    
  2. 在顶部声明$cString并通过引用传递:

    $cString = '';
    function my_fn(&$cString) {
        $cString = 'abc';
    }
    my_fn($cString);
    
  3. 我遗漏了使用global,因为我觉得这不适合你的情况。

答案 2 :(得分:0)

问题是你的变量在if内,当你在它外面调用它时就不存在了。您只需要在if之外声明变量(在代码的开头就是完美的)。

答案 3 :(得分:0)

我解决了这个问题!感谢大家的帮助,问题在于代码中的逻辑。