【问题标题】:Insert values into one table from form and other multiple other tables将值从表单和其他多个其他表中插入到一个表中
【发布时间】:2016-06-05 06:06:26
【问题描述】:

我有一个包含三个输入的表单。两个下拉菜单和一个文本输入。下拉列表在显示之前从我的数据库中填充。文本输入是来自用户的新数据。用户将向我的数据库添加新资产,但必须选择项目的制造商和类别。

添加资产后,我希望更新资产表。我被困在如何使用表单数据和下拉列表中的现有值插入我的asset_names 表。我需要取值、用户友好的词,并从各自的数据库中选择相应的 ID。

INSERT INTO asset_names (asset_name, asset_category_id, asset_manufacturer_id, asset_status_id)
VALUES ( :newAssetName,
        ( SELECT category_id FROM asset_categories WHERE category_name=:newAssetCategory),
        ( SELECT manufacturer_id FROM manufacturers WHERE name=:newAssetManufacturer),
        1)";
$stmt = $pdo->prepare( $sql );

//Bind value.
$stmt->bindValue( ':newAssetName',     $newAssetName  );
$stmt->bindValue( ':newAssetCategory', $newAssetCategory );
$stmt->bindValue( ':newAssetManufacturer', $newAssetManufacturer );


//Execute.
$stmt->execute();

如果我将值硬编码到语句变量中,则该语句有效。现在几乎就像变量为空一样。

【问题讨论】:

  • :newAssetManufacture != :newAssetManufacturer.
  • @chris85,我修正了那个错字。
  • 好的,那么现在这段代码会发生什么?它抛出一个错误?插入错误的数据?为什么要有子查询,只要把id作为option的值放在表格里就行了。
  • @chris85,发生的情况是,当我提交表单时,字段被插入到数据库中,但变量 :newAssetCategory 和 :newAssetManufacturer 的值输入为 0。我不确定在哪里0 来自。我正在使用 select 语句,因为我需要从下拉列表中获取字符串并使用它们来查找它们各自的行 ID。我已经根据自动递增的行 ID 制作了表键。
  • 为什么需要字符串而不是整数?

标签: php sql pdo


【解决方案1】:

而不是使用子查询。只需将数据传递给 DOM。

<option value="<?php echo $id;?>"><?php echo $stringversion;?></option>

那么你可以按预期绑定值。

"INSERT INTO asset_names (asset_name, asset_category_id, asset_manufacturer_id, asset_status_id)
VALUES ( :newAssetName,
        :newAssetCategory),
        :newAssetManufacturer),
        1)";
$stmt = $pdo->prepare( $sql );
//Bind value.
$stmt->bindValue( ':newAssetName', $newAssetName  );
$stmt->bindValue( ':newAssetCategory', $newAssetCategory );
$stmt->bindValue( ':newAssetManufacturer', $newAssetManufacturer );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    相关资源
    最近更新 更多