gpt4 book ai didi

php - 将多行表存储到数组中以允许用户更新

转载 作者:行者123 更新时间:2023-11-30 21:45:45 24 4
gpt4 key购买 nike

我已经为这个概念苦苦挣扎了一段时间,希望有人能提供帮助。如果所有值都存储在一行中,我可以查询数据库记录。我面临的挑战是当数量值存储在多行但具有公共(public)键(例如 order_id)时。我想存储到一个数组中,然后将每个值分配给一个屏幕变量以允许用户更新,以便我可以再次更新表。

例如,如果表格如下所示:

    id  line    part    qty
-- ---- ---- ---
1 1 63 2
1 2 104 3
1 3 54 2
1 4 50 1

我在确定行数然后尝试构建 foreach 循环以捕获数据的情况下没有成功:

    $sql = 'SELECT *, COUNT(*) as $count FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);

for ($x = 0; $x <= $count; $x++ {
$var($x) = $data['qty'];
}

如果我可以将这些值正确地分离到一个数组中,然后以某种方式引用它们,那么我可以执行以下操作并显示它们并轻松更新回数据库:

$var_1  = $data['63'];  // part_id = 63
$var_2 = $data['104']; // part_id = 104
$var_3 = $data['54']; // part_id = 54
$var_4 = $data['50']; // part_id = 50

最佳答案

改变这个:

$sql = 'SELECT *, COUNT(*) as $count FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);

for ($x = 0; $x <= $count; $x++ {
$var($x) = $data['qty'];
}

像这样有意义的事情

$sql = 'SELECT * FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
while(false !== ($row = $q->fetch(PDO::FETCH_ASSOC))){
echo $row['qty'];
};

更新

$sql = 'SELECT * FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$array = [];
while(false !== ($row = $q->fetch(PDO::FETCH_ASSOC))){
$array['line_'.$row['line']] = $row;
};

更新

回答我正在寻找的内容的附加代码如下。您的回答是我理解这一切的关键:

$sql = 'SELECT * FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$array = [];
while(false !== ($row = $q->fetch(PDO::FETCH_ASSOC))){
$qty['line_'.$row['line']] = $row['qty'];
};

$var_54 = $qty['line_54'];
$var_63 = $qty['line_63'];

关于php - 将多行表存储到数组中以允许用户更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49565097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com