带有MYSQL中选定数据的表单出现问题

hlswsv35  于 2023-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(162)

当我从表格中的数据中选择“货币”时,我有一个好的值“float(55)是输入的值float(4.68)是从选择float(0.03)是从第二次选择”,但是当我发布这个表格时,我的值更改为这个“string(4)”3.20“string(4)”0.13“。只有表格中的值是好的。
下面是我的代码:
Calculator.Currencies:

<?php

include_once __DIR__ . '/../../database/CurrenciesTable.php';
class CalculatorCurrencies extends \CurrenciesTable
{
    public $selected_current;

    public  $current_currency;

    public  $calculated_value;

    public int $score;

    public function __construct(  $current_currency,  $selected_current,  $calculated_value)
    {
        $this->current_currency = $current_currency;
        $this->selected_current = $selected_current;
        $this->calculated_value = $calculated_value;
    }

    private $errors = array(
        "empty" => "Inputs can't be empty",
        "numeric" => "Inputs must be numeric"

    );
    public function calc()
    {
        $check = true;
        if($this->validationCalc() == false){
            return $this->errors['empty'];
            $check = false;
        }
        if($this->valIsFloat() == false){
            return $this->errors['numeric'];
            $check = false;
        }if($check == true){

            $scoress = new CurrenciesTable();
            $endvalue = $scoress->getCurrencies();

            $currentRate= $endvalue[$this->selected_current]['rate'];
            $targetRate = $endvalue[$this->calculated_value]['rate'];

            var_dump($currentRate);
            var_dump($targetRate);

            $this->score = $this->current_currency * ($currentRate / $targetRate);
            return $this->score;

        }

    }

    public function validationCalc(){
        $calc = true;
        if(empty($this->current_currency) || empty($this->selected_current)){
            $calc = false;
        }else{
            $calc  = true;
        }
        return $calc;
    }

    public function valIsFloat()
    {
        $calcNum = true;
        if (!is_float($this->current_currency)) {
            $calcNum = false;
        }else{
            $calcNum = true;
        }
        return $calcNum;
    }



}

Calculator.php:

<?php
include_once __DIR__ . '/../../src/classes/CalculatorCurrencies.php';
include_once __DIR__ . '/../../database/CurrenciesTable.php';

//Przesłanie formularza, sprawdź czy są przesłane dane.
if (isset($_POST['Calculate'])) {

    //Wartość do obliczenia
    $current = floatval($_POST['current_currency']);
    //Wybrana waluta
    $selected_current = floatval($_POST['current_select']);
    // Docelowa waluta
    $selected_target = floatval($_POST['target']);


    $score = new CalculatorCurrencies($current,$selected_current,$selected_target);
    $Calculate =$score->calc();
    var_dump($current);
    echo ('to wartosc wpisana');
    var_dump($selected_current);
    echo ('to z selecta');
    var_dump($selected_target);
    echo ('to z drugiego selecta');

}
$show = new CurrenciesTable();
$currency = $show->getCurrencies();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <title>Title</title>
</head>
<body>

<div>
    <form id="4" method="POST">
        <div class="mb-3">
            <label for="current_currency" class="form-label">Current Currency</label>
            <input type="number" class="form-control" name="current_currency" id="current_currency">
            <select class="form-select" id="current_select" name="current_select" aria-label="Default select example">
                <option selected>Wybierz Walutę</option>
                <?php foreach($currency as $result) :?>
                <option value="<?php echo $result['rate']?>"><?php echo $result['currency']?></option>
                <?php endforeach ;?>
            </select>
        </div>
        <div class="mb-3">
            <select class="form-select" id="target" name="target" aria-label="Default select example">
                <option selected>Wymień na</option>
                <?php foreach($currency as $result) :?>
                    <option value="<?php echo $result['rate']?>"><?php echo $result['currency']?></option>
                <?php endforeach ;?>
            </select>
        </div>
        <button class="p-2 m-3 align-content-end d-flex" id="Calculate" type="submit" name="Calculate">Calculate</button>
        <label for="Score" class="form-label center">Wartość: <?php if(isset($score->score)){ echo $score->score;} ?></label>
    </form>
</div>
</body>
</html>

和CurrenciesTable.php:

<?php

include_once __DIR__ . '/Connect.php';
class CurrenciesTable extends \Connect
{

    public function getTableData($limit, $offset) {
        $query = "SELECT effective_date, currency, code, rate FROM kurs_walut LIMIT :limit OFFSET :offset";
        $countQuery = "SELECT COUNT(*) as count FROM kurs_walut";

        $statement = $this->conn->prepare($query);
        $statement->bindParam(':limit', $limit, \PDO::PARAM_INT);
        $statement->bindParam(':offset', $offset, \PDO::PARAM_INT);
        $statement->execute();
        $results = $statement->fetchAll();

        $countStatement = $this->conn->prepare($countQuery);
        $countStatement->execute();
        $countResult = $countStatement->fetch();
        $totalRecords = $countResult['count'];


        return [
            'data' => $results,
            'totalRecords' => $totalRecords
        ];
    }

    public function getCurrencies(){
        $query = "SELECT currency, rate FROM kurs_walut";
        $statement = $this->conn->prepare($query);
        $statement->execute();
        $results = $statement->fetchAll(PDO::FETCH_ASSOC); // Użyj FETCH_ASSOC, aby otrzymać wyniki w postaci asocjacyjnej

        return $results; // Zwróć wyniki bez dodatkowego opakowania
    }

}

我改变了优先级发送值,改变了数据库中的结构,并在类中编码,但现在我不知道如何修复它。

hrirmatl

hrirmatl1#

根据提供的代码,有几个问题可能导致在提交表单时货币值发生更改。以下是解决此问题的一些建议:
删除Calculator.php文件中不必要的floatval转换:

$current = $_POST['current_currency'];
$selected_current = $_POST['current_select'];
$selected_target = $_POST['target'];

$_POST超全局变量已经返回了字符串值,所以你不需要使用floatval来转换它们。
更新CalculatorCurrencies类中的valIsFloat方法,以检查值是否为数值,而不是专门检查浮点数:

public function valIsFloat()
{
    return is_numeric($this->current_currency);
}

更改HTML表单中元素的value属性,使其与货币代码而不是汇率相对应。这将允许您从表单中检索选定的货币代码,并使用它从CalculatorCurrencies类的数据库中获取相应的汇率。

<option value="<?php echo $result['code'] ?>"><?php echo $result['currency'] ?></option>

修改CalculatorCurrencies类中的calc方法,以基于所选货币代码检索汇率:

$currentRate = $endvalue[$this->selected_current]['rate'];
$targetRate = $endvalue[$this->calculated_value]['rate'];

用下面的代码替换上面的行:

$currentRate = $scoress->getRateByCurrencyCode($this->selected_current);
$targetRate = $scoress->getRateByCurrencyCode($this->calculated_value);
Add a new method getRateByCurrencyCode to the CurrenciesTable class to fetch the rate based on the currency code:
public function getRateByCurrencyCode($currencyCode)
{
    $query = "SELECT rate FROM kurs_walut WHERE code = :code";
    $statement = $this->conn->prepare($query);
    $statement->bindParam(':code', $currencyCode);
    $statement->execute();
    $result = $statement->fetch(PDO::FETCH_ASSOC);
    return $result['rate'];
}

通过进行这些更改,您应该能够根据选定的货币代码检索正确的汇率,并准确地执行计算。

相关问题