如何使用 PHP 将两个字段中的值相除并将结果插入到另一个字段中


How to divide values in two field and insert the result to another field using PHP

我需要将 ProductID 的值和成本相除。

下面是我的代码示例:

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "testting";
$a = "calculationexample.ProductID";
$b = "calculationexample.Cost";
$c = "(a/b)";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO calculationexample (ProductID, Cost, Ratio)
VALUES ('400', '200', '$c')";
// use exec() because no results are returned

$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

为"产品 ID"、"成本"字段(比率除外)字段正确插入该值。谁能告诉我正确的方法?

谢谢。

=== 问题已更新 ====

<?php
    require 'database.php';

    if ( !empty($_POST)) {
        // keep track validation errors
        $ProductIDError = null;
        $CostError = null;
        $MonthError = null

        // keep track post values
        $ProductID = $_POST['ProductID'];
        $Cost = $_POST['Cost'];
        $Month = $_POST['Month'];

        // validate input
        $valid = true;
        if (empty($ProductID)) {
            $ProductIDError = 'Please enter product id';
            $valid = false;
        }

        $valid = true;
        if (empty($Cost)) {
            $CostError = 'Please enter cost value';
            $valid = false;
        }

        $valid = true;
        if (empty($Month)) {
            $MonthError = 'Please enter cost value';
            $valid = false;
        }

$conn= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$var = "John"; // based on an id column (varchar)
    $stmt = $conn->prepare('SELECT Month,ProductID,Cost,Ratio FROM Inventory');
   // $stmt->bindValue(1, $var); 
    $stmt->execute();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$a = $row['ProductID'];
$b = $row['Cost'];
$m =$row['Month']
$c = ($a/$b);
//echo $c; // will output the ratio
            }
}

    try {

    $stmt = $conn->prepare("INSERT INTO Inventory 
    (Month,ProductID, Cost, Ratio)
    VALUES(:Month, :ProductID, :Cost, :Ratio)");
    $stmt->bindValue(':Month', $m,PDO::PARAM_INT);    
    $stmt->bindValue(':ProductID', $a,PDO::PARAM_INT);
    $stmt->bindValue(':Cost', $b,PDO::PARAM_INT);
    $stmt->bindValue(':Ratio', $c,PDO::PARAM_INT);
    $stmt->execute();
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">
                <div class="span10 offset1">
                    <div class="row">
                        <h3>Inventory</h3>
                    </div>

                    <form class="form-horizontal" action="division.php" method="post">
                      <div class="control-group <?php echo !empty($MonthError)?'error':'';?>">
                        <label class="control-label">Month</label>
                        <div class="controls">
                            <input name="month" type="text"  placeholder="Month" value="<?php echo !empty($m)?$m:'';?>">
                            <?php if (!empty($MonthError)): ?>
                                <span class="help-inline"><?php echo $MonthError;?></span>
                            <?php endif; ?>
                        </div>
                      </div>

                      <div class="control-group <?php echo !empty($ProductID)?'error':'';?>">
                        <label class="control-label">ProductID</label>
                        <div class="controls">
                            <input name="ProductID" type="text" placeholder="ProductID" value="<?php echo !empty($ProductID)?$ProductID:'';?>">
                            <?php if (!empty($ProductIDError)): ?>
                                <span class="help-inline"><?php echo $ProductIDError;?></span>
                            <?php endif;?>
                        </div>
                      </div>

                      <div class="control-group <?php echo !empty($Cost)?'error':'';?>">
                        <label class="control-label">Cost</label>
                        <div class="controls">
                            <input name="Cost" type="text"  placeholder="Cost" value="<?php echo !empty($Cost)?$Cost:'';?>">
                            <?php if (!empty($CostError)): ?>
                                <span class="help-inline"><?php echo $CostError;?></span>
                            <?php endif;?>
                        </div>
                      </div>

                      <div class="form-actions">
                          <button type="submit" class="btn btn-success">Daftar</button>
                          <a class="btn" href="index.bulanan.php">Menu Utama</a>
                        </div>
                    </form>
                </div>
    </div> <!-- /container -->
  </body>
</html>

您首先需要做的是查询数据库,以便从"产品 ID"和"成本"列中获取值,以便能够获取要在表中输入的比率。

正如我在评论区域中概述的那样,您需要将$c = "(a/b)";更改为$c = ($a/$b);

就目前而言,"a"和"b"都被视为常量,并在引号内设置时被视为字符串。

如果在引号内设置,$c = "($a/$b)";将产生 (10/50),而$c = ($a/$b);将根据使用$a = 10; $b = 50;生成 0.2

要采取的步骤:

  • 查询您的表
  • 计算列中的值(必须是整数)
  • 将查询表中的结果值插入到所需表中

旁注:不确定 400 和 200 ('400', '200', '$c')在那里做什么,以及这些是否是您希望用作比率的数字。您可能需要详细说明。

您的比率列需要为十进制 50,2/50 是一个夸张的数字,但 2 将是小数点。

注意:比率会产生小数。

附加说明:下面的$var = "John";基于id列(VARCHAR

例如:

<?php
$mysql_hostname = 'xxx';   // change
$mysql_username = 'xxx';   // to
$mysql_password = 'xxx';   // your
$mysql_dbname   = 'xxx';   // own
$conn= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$var = "John"; // based on an id column (varchar)
    $stmt = $conn->prepare('SELECT Cost, ProductID FROM calculationexample WHERE id = ?');
    $stmt->bindValue(1, $var); 
    $stmt->execute();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$a = $row['Cost'];
$b = $row['ProductID'];
$c = ($a/$b);
echo $c; // will output the ratio
            }
try {
    $prod_id = 400;
    $cost = 200;
    $stmt = $conn->prepare("INSERT INTO calculationexample 
    (ProductID, Cost, Ratio)
    VALUES(:prod_id, :cost, :ratio)");
    $stmt->bindValue(':prod_id', $prod_id,PDO::PARAM_INT);
    $stmt->bindValue(':cost', $cost,PDO::PARAM_INT);
    $stmt->bindValue(':ratio', $c,PDO::PARAM_INT);
    $stmt->execute();
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>