开发者

My simple PHP function for maintaining values in my form isn't working. Really newbie!

开发者 https://www.devze.com 2022-12-20 13:03 出处:网络
Here\'s my code: <html> <head> <?php function getValue($field){ if(isset($_GET[$field])){ ret开发者_StackOverflow社区urn $_GET[$field];

Here's my code:

<html>
<head>
    <?php
    function getValue($field){
        if(isset($_GET[$field])){
            ret开发者_StackOverflow社区urn $_GET[$field];
        }
        else{
            return "";
        }
    }

    ?>
</head>

<body>
    <form action="class2.php" method="get">
        <dl>
            <dt>First Name:</dt>
            <dd><input type="text" value="<?php echo htmlspecialchars(getValue($_GET['name'])) ?>" name="name" />                    
            </dd>                

            <dt>Last Name:</dt>
            <dd><input type="text" value="<?php echo htmlspecialchars(getValue($_GET['lastname'])) ?>" name="lastname" />                    
            </dd>

            <br />                
            <dt>
                <input type="submit" value="enviar" />
            </dt>                
        </dl>
    </form>
</body>

If I write a value in Name and nothing in LastName, the value in Name SHOULD stay there, right? What am I doing wrong?


getValue('name') not getValue($_GET['name']);


Your problem is that you are using

getValue($_GET['name'])

instead of

getValue( 'name' )

You are calling getValue() with the contents of $_GET['name'] right now

Also: Your getValue function doesn't make much sense right now. Why not build in htmlspecialchars() into it directly instead of applying it to its return value?


Firstly, do you really need a function just to retrieve an elem of the $_GET array?

Because you're reading a GET request, if you refresh this page and don't submit your form (and clear the query string), you'll lose your data in $_GET.

If you want to keep hold of this information, you can place it in the session ($_SESSION).

Don't forget to filter your input and escape your output.


Within the <dd><input... tags, that PHP should read:

<dd><input type="text" value="<?php echo htmlspecialchars(getValue( 'name' )) ?>" name="name" />

The function you wrote knows to take that value name, and look for it within the GET array, no need to tell it to do that when you call it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号