tags:

views:

41

answers:

4

Here's my code:

<html>
<head>
    <?php
    function getValue($field){
        if(isset($_GET[$field])){
            return $_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?

+1  A: 

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?

lamas
+1  A: 

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

thetaiko
A: 

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.

Greg K
A: 

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.

Alex Mcp