如何添加到数据库中的现有值

时间:2012-11-01 09:07:05

标签: php mysql database sql-update insert-update

我回到了另一个绝对的初学者问题,我将值存储在数据库中,我的目标是允许用户使用下拉菜单减去或添加到特定数据库值(数量),其值范围从1 - 10.我现在保持简单。

mysql_select_db("toner", $con);
$sql=INSERT INTO inventory (partnumber, quantity)
VALUES
('$_POST[partnumber]','$_POST[quantity]');
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);

我可以找到很多例子,只是添加或删除静态值,但这不是我需要的。我搜索了几个类似于我正在寻找的例子1& 2似乎UPDATE是最好的解决方案但是我不确定它应该如何实现,我也在考虑连接,但我不确定它能否实现我需要的任何帮助你可以提供这个新手表示赞赏。感谢

2 个答案:

答案 0 :(得分:2)

要使以下解决方案起作用,您需要在数据库中插入一个值,例如partnumber = 1和qantity = 0.您肯定需要修改它以使用您的mysql连接字符串并且需要查看数据库之后检查它是否有效或添加选择查询。但是,这将使用下拉列表中选择的数量更新库存项目1的数量...

file.php

<?php
    include("db_connection_file.php"); // in here are the username and password etc for your mysql connection
    if($_POST){ // the code in this block will ONLY fire if the form has been posted
        $dropdown_contents = $_POST['drop']; // this is the value of the form item 'drop' that has been posted...
        $part_no_from_form = $_POST['part_no'];
        $query ="UPDATE inventory SET quantity = '".$dropdown_contents."' WHERE partnumber = '".$part_no_from_form ."'"; // this updates the database and sets the quantity to that posted where the part number is that in the form
        $testResult = mysql_query($query) or die('Error, query failed'); 
        echo "This worked";
    }
?>
<form acion="file.php" method="post">
    Quantity <select name="drop" id="drop">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
        <option>6</option>
        <option>7</option>
        <option>8</option>
        <option>9</option>
        <option>10</option>
    </select><br />
    Part No. <select name="part_no" id="part_no">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
        <option>6</option>
        <option>7</option>
        <option>8</option>
        <option>9</option>
        <option>10</option>
    </select><br />
    <input type="submit" value="go" />
</form>

注意:这可以很容易地扩展,通过添加另一个下拉列表或输入框来指定要在数据库中更新的部分号,捕获已发布的值并将其传递给Update查询的where部分。

这没有任何确认!它还使用折旧的MySQL连接函数,请查阅MySQLi和PDO

答案 1 :(得分:0)

将行更新为新的KNOWN值:

UPDATE inventory SET quantity = $KnownValue WHERE partnumber = $PartNumber;

要更新添加到现有值的行,即向库存添加了另外5个单位:

UPDATE inventory SET quantity = quantity + $IncramentalValue WHERE partnumber = $PartNumber;
相关问题