gpt4 book ai didi

php/mysql 二变量数组

转载 作者:行者123 更新时间:2023-11-29 06:05:56 25 4
gpt4 key购买 nike

我允许用户使用表单中的文本框创建最多十个类别。为此,我有十个文本框,其形式为 name = cat[]。当他们第一次输入类别时——无论数量有多少,最多可达十个,在接收端,我只是收集类别数组并使用插入语句将它们保存到类别表中。到目前为止,一切都很好。

但是,现在我想让他们更改已经设置的类别或添加最多十个额外类别。他们已经设置的类别有 id。因此,我将 ID 与类别名称一起回显到表单中。我的问题是现在如何收集姓名和 ID?需要插入新的并且可能需要更新表中现有的?出于某种原因,我完全不知道如何做到这一点。这就是我到目前为止所拥有的>

餐 table 上的猫

id | catname | userid

表单页面:

//retrieve existing cats if any...also get catids

echo '<form action = storecats.php method=post>';
$i=1;
//Get all existing cats
while($row = mysql_fetch_array($res))
{
$catname = $row['catname'];
$catid = $row['id'];
echo '<input type = "text name="cat[]" value="'.$catname.'">Cat 1';
echo '<input type="hidden" name="id[]" value = "'.$catid.'">';
$i = $i+1;
}
//empty boxes up to ten.
while($i <= 10){
echo '<input type="text" size=18 name="cat[]" value=""> Cat '.$i.'<br>';
$i = $i+1;
}//end appending of blank categories
echo '<input type="submit" name="submit" value="submit"></form>';

在接收端,我可以收集 cat 和 id 的数组。

$idarray = $_POST['id']; //there will be as many elements as there were ids
$catarray = $_POST['cat']; //there will be ten elements in array

如果有 id,我想执行更新,而如果没有 id,我想插入,除非该值为空。

我的问题是我不知道如何链接不同数组中收到的 id 和猫名称。请注意,总会有 10 个猫名,但该用户的 ID 数量与之前表中的数量相同。

最佳答案

您可以在 HTML 端使用 2 个数组来实现:

    $x=0;
while ($row = mysql_fetch_array($res))
{
echo '<input type="text" name="updateCat['.$row["id"].']" value="'.$row["catname"].'"> Cat Name';
$x++;
}

// new ones
for(;$x<10;$x++)
{
echo '<input type="text" name="newCat[]">';
}

在 php 端:

    // update old categories
foreach ($_POST["updateCat"] as $key => $value)
{
mysql_update ("UPDATE table SET name = $value WHERE id = $key");
}

// insert
foreach ($_POST["newCat"] as $value)
{
mysql_update ("INSERT INTO table {...}");
}

插入新类别时,您还检查了类别不超过 10 个。

关于php/mysql 二变量数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11505565/

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