artmem
artmem

Reputation: 367

Use form input to build url with php.

I'm trying to create a form where the user can input their id (username) and it will be appended as a variable in a url that is used in my php script. This is what I have.

<?php
if(isset($_POST['submit']))
{
    $id = $_POST['id'];
    echo 'http://example.com/default.asp?action=data&id=$id';
}
?>
<form method="post" action="<? echo $_SERVER['PHP_SELF']; ?>">
   <input type="text" name="id"><br>
   <input type="submit" name="submit" value="Submit Form"><br>
</form> 

It collects the user's id properly, and if i just echo $id, it outputs the proper value, but when I try to echo the url, it just outputs $id instead of the actual value of the $id variable. What am I doing wrong?

Upvotes: 0

Views: 3424

Answers (3)

Caleb Taylor
Caleb Taylor

Reputation: 177

This line:

echo 'http://example.com/default.asp?action=data&id=$id';

Should be

echo 'http://example.com/default.asp?action=data&id='.$id;

If you are using single quotes in PHP with a string it will print whatever is inside the string without evaluating anything (ie no variables are evaluated). So you can either use double quotes or append the variable like I did above.

Upvotes: 1

citruspi
citruspi

Reputation: 6891

Single quotes won't interpolate the variable, either use double quotes or use string concatenation.... Three options:

    echo "http://example.com/default.asp?action=data&id=".$id;

or

    echo "http://example.com/default.asp?action=data&id=$id";

or

    echo 'http://example.com/default.asp?action=data&id='.$id;

Upvotes: 1

Marc B
Marc B

Reputation: 360882

echo "http://example.com/default.asp?action=data&id=$id";
     ^---wrong quotes                                  ^--- ditto

single-quoted strings do not interpolate variables.

Upvotes: 5

Related Questions