clarent
clarent

Reputation: 21

Can't access form data in PHP

I'm not a novice, but I'm not an expert either; I'm a keen learner.

Problem (minimalised) - I have a basic form which posts a name to another page which is supposed to receive name and print name. Code of both forms is below.

Form:

<?php
    echo "Hello, World!";
    echo "
        <form action='CFAcomments.php' method='POST'>
            <table style='width: 50%;' border='0'>
                <tbody>
                    <tr>
                        <td><label for='name'>name: </label></td>
                        <td><input type='Text' name='name' value='anon' /></td>
                    </tr>
                    <tr>
                        <td><input type='submit' name='send' value='Send' /></td>
                    </tr>
                </tbody>
            </table>
        </form>
    ";
?>

Form Process:

<?php
    echo "Hello, World 1!";
    echo "<br/>";
    var_dump($_POST);
    $name = $_POST("name");
    echo "Hello $name!";
?>

Result:

Hello, World 1!
array(2) { ["name"]=> string(11) "anon" ["send"]=> string(4) "Send" }

Problem:

Even though var_dump($_POST) shows data being sent, echo $name print nothing. Changing echo $name to echo "test" prints nothing too. The code seems to stop executing at $name = $_post("name");. If I remove this line echo "anything" works.

I've used PHP and forms for the last two years and never come across this. Any help would be appreciated.

Upvotes: 2

Views: 1280

Answers (7)

J0HN
J0HN

Reputation: 26941

To access array's element you have to use square brackets. So, it's just replacing

$name = $_POST("name");

with

$name = $_POST["name"];

Upvotes: 1

MattBelanger
MattBelanger

Reputation: 5350

This needs to be

$name = $_POST["name"];

Note the square brackets, because $_POST is an array, not a function.

Upvotes: 1

theprogrammer
theprogrammer

Reputation: 2734

You need to use

$_POST["name"];

$_POST is an associative array of variables passed to the current script via the HTTP POST method.

See: http://php.net/manual/en/reserved.variables.post.php

Upvotes: 1

Nemanja
Nemanja

Reputation: 1535

$name = $_POST("name"); 

is not the correct way. It should be:

$name = $_POST["name"]; 

since $_POST is an array.

Upvotes: 1

Garvin
Garvin

Reputation: 487

You are using the incorrect syntax for $_POST. It should be

 <?php
    $name = $_POST["name"]; 
    echo "hello $name !"; 
 ?>

You are accessing it like a function instead of an array.

Upvotes: 1

markus
markus

Reputation: 40675

That's because you're not using the right brackets. It has to be:

$_POST['name'];

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270637

Array keys are referenced with square brackets, not parentheses.

$name = $_POST("name");

// Should be
$name = $_POST["name"];

Upvotes: 4

Related Questions