使用关联数组显示和更新数据库

时间:2018-01-24 16:41:24

标签: php mysql multidimensional-array pdo

在我的代码中,我已经收到了用户的输入并将数据保存到数据库中。

现在我想允许用户更新交易。使用以下代码我在屏幕上显示100个部件号(我只显示部分片段)。如果$ _POST值有效,我更新表。否则,我允许用户输入更新字段。

pnum数量
1 - 3
2 - 5
3 - 9

我的问题有两个: (1)如果我在数据库中存储了100个部件号,是否需要100个if-then-else语句来解析数组数据才能在屏幕上显示? (2)我还需要另外100个if-then-else语句来将数据更新回数据库表吗?

<?php
  if ( !empty($_POST)) {
$Error_part_no_1 = null;
$Error_part_no_2 = null;
$part_no_1 = $_POST['part_no_1];
$part_no_2 = $_POST['part_no_2];

    if ($valid) {
        $sql = "UPDATE (table)  SET qty = ?";

  } else {
$sql = "SELECT  * FROM (table)";
$q = $pdo->prepare($sql);
$q->execute(array());

while ($row = $q->fetch(PDO::FETCH_ASSOC))
{
   if ($row['part_num'] == 'part_no_1' {$part_no_1 = $row['qty'];} 
   if ($row['part_num'] == 'part_no_2' {$part_no_2 = $row['qty'];} 
    }
  }
?>
<form class="form-horizontal" action="update.php?id=<?php echo $id?>" method="post">
    <div class="control-group <?php echo !empty($Error_part_no_1)?'error':'';?>">
        <label class="control-label">Part No 1</label>
        <div class="controls">
            <input name="part_no_1" type="text"  placeholder="" value="<?php echo !empty($part_no_1)?$part_no_1:'';?>">
            <?php if (!empty($Error_part_no_1)): ?>
               <span class="help-inline"><?php echo $Error_part_no_1;?></span>
            <?php endif; ?>
        </div>
    </div>
</form>

1 个答案:

答案 0 :(得分:0)

你基本上想要混合/匹配while循环。理想情况下,数组的键应该是PART NUMBER或唯一标识符,这使得它更容易使用。 foreach,in_array()和while循环是你的朋友。如下所示:

<?php
  if ( !empty($_POST)) {

    if ($valid) {
        //LOOP through $_POST with foreach, update the table accordingly
        foreach ( $_POST as $partNo => $val ) {
            $sql = "UPDATE (table) SET qty = ? WHERE part_no = ?";
            //Execute
        }
  } else {
$sql = "SELECT  * FROM (table)";
$q = $pdo->prepare($sql);
$q->execute(array());


?>
<form class="form-horizontal" action="update.php?id=<?php echo $id?>" method="post">
   <?php while ($row = $q->fetch(PDO::FETCH_ASSOC)): ?>
    <div class="control-group <?php echo in_array($emptyErrors, $row['part_no'])?'error':'';?>">
        <label class="control-label">Part No 1</label>
        <div class="controls">
            <input name="<?php echo $row['part_no'] ?>" type="text"  placeholder="" value="<?php echo !empty($row['part_no'])?$row['part_no']:'';?>">
            <?php if (in_array($emptyErrors, $row['part_no'])): ?>
               <span class="help-inline">Part number <?php echo $row['part_no'];?> cannot be empty.</span>
            <?php endif; ?>
        </div>
    </div>
   <?php endwhile; ?>
</form>