1

我只是学习html。我需要编写解决二次方程公式的代码。我尝试在 html 中嵌入 php 代码,但得到空白输出。如何获取用户值 a、b、c 并显示条件答案?

4

3 回答 3

3

这是您需要做的一个简单示例。首先制作一个 HTML 表单:

<form method="post" action="index.php">
    <input type="text" name="a" value="Enter 'a'" />
    <input type="text" name="b" value="Enter 'b'" />
    <input type="text" name="c" value="Enter 'c'" />
    <input type="submit" name='calc' value="Calculate" />
</form>

有你的表格。现在计算:

<?php
if (isset($_POST['calc'])) //Check if the form is submitted
{
    //assign variables
    $a = $_POST['a'];
    $b = $_POST['b'];
    $c = $_POST['c'];
    //after assigning variables you can calculate your equation
    $d = $b * $b - (4 * $a * $c);
    $x1 = (-$b + sqrt($d)) / (2 * $a);
    $x2 = (-$b - sqrt($d)) / (2 * $a);
    echo "x<sub>1</sub> = {$x1} and x<sub>2</sub> = {$x2}";
} else {
    //here you can put your HTML form
}
?>

您需要对其进行更多检查,但正如我之前所说,这是一个简单的示例。

于 2012-02-26T16:31:38.513 回答
0

我有更小的例子。

该文件将数据从表单发送到自身。当它发送一些东西时 - 条件的结果

$_SERVER['REQUEST_METHOD']=='POST'

是真的。如果它是真的 - “if”块中的服务器进程代码。它将表单发送的数据分配给 2 个变量,然后将它们相加并存储在“$sum”变量中。结果显示。

<html>
    <body>    
        <form method="POST">

            <p>
            A: <br />
                <input name="number_a" type="text"></input>
            </p>

            <p>B: <br />
                <input name="number_b" type="text"></input>
            </p>

            <p>
                <input type="submit"/>
            </p>

        </form>

<?php


    if ($_SERVER['REQUEST_METHOD']=='POST') // process "if block", if form was sumbmitted
    {
        $a = $_POST['number_a'] ; // get first number form data sent by form to that file itself
        $b = $_POST['number_b'] ; // get second number form data sent by form to that file itself

        $sum = $a + $b;  // calculate something

    echo "A+B=" . $sum; // print this to html source, use "." (dot) for append text to another text/variable
    }

?>

    </body>
</html>

您需要 PHP 服务器来测试/使用它!PHP文件必须由创建页面的Web服务器处理。从磁盘打开 php 文件将不起作用。如果您需要更多解释 - 在评论中询问。

于 2012-02-26T16:39:43.180 回答
0

编辑:学习源码,php官方网站: http: //php.net/manual/en/tutorial.forms.php

1.创建一个包含所需字段的表单。<form method='post' ....>...</form>

2.用户提交表单,然后编写一个PHP代码,获取发布的数据($_POST)并根据二次方程公式对其进行操作。

3.Echo结果。

于 2012-02-26T16:24:02.710 回答