将用户输入分配给php中的变量

时间:2015-06-04 03:40:27

标签: php command-line-interface

构建我的第一个php程序,面临的问题是将用户输入分配给变量

这是我的代码

<?php
printf("Enter student test mark");
$test = read_stdin();

    function read_stdin()
{
        $fr=fopen("php://stdin","r");   // open our file pointer to read from stdin
        $input = fgets($fr,128);        // read a maximum of 128 characters
        $input = rtrim($input);         // trim any trailing spaces.
        fclose ($fr);                   // close the file handle
        return $input;                  // return the text entered
}



printf("Enter student assignment mark");

?>

如何让用户输入数字并将其分配给测试变量

2 个答案:

答案 0 :(得分:1)

<?php

    if(isset($_POST['submit']))
{
        $test = $_POST['marks'];//assigning your input value

        if(isset($test))
        {
            $fr=fopen("php://stdin","r");   // open our file pointer to read from stdin
            $input = fgets($fr,128);        // read a maximum of 128 characters
            $input = rtrim($input);         // trim any trailing spaces.
            fclose ($fr);                   // close the file handle
            $result =  $input;              // return the text entered
        }
    }

?>
<form action="#" method="post">
    <input type="text" name="marks" placeholder="Enter student test mark">
    <input type="submit" name="submit" value="submit">
</form>


<?php
if(empty($result))
{

}
else
{
  echo ' Enter student assignment mark';
}

或者您可以先显示所有输入框,然后分配给您的变量并进行计算

答案 1 :(得分:0)

这是我在那里测试代码的示例,您的代码似乎正在运行..

sample.php [DIR]

中命名此/Users/xxxxxxxxx/Desktop [FILE] <{1>}

下的

Terminal.app
  

sample.php

cd [DIR] // cd  /Users/xxxxxxxxx/Desktop

php [FILE] // php sample.php
  

示例输出

<?php

    function read_stdin()
    {
        $fr=fopen("php://stdin","r");   // open our file pointer to read from stdin
        $input = fgets($fr,128);        // read a maximum of 128 characters
        $input = rtrim($input);         // trim any trailing spaces.
        fclose ($fr);                   // close the file handle
        return $input;                  // return the text entered
    }

    printf("Enter 1st number:");
    $num1 = read_stdin();

    printf("Enter 2nd number:");
    $num2 = read_stdin();

    echo "Equation: ".$num1." + ".$num2." = ".($num1 + $num2)."\n";

?>