我正在尝试通过使用数组来更新数据。基础是我有一个如下所示的表格:
|| idtest || testfieldA || testfieldB || testfieldC || externalId ||
其中 idtest 是主键,外部 id 是与另一个表的主键相关的 id,因此行 idtest = 1、2 和 3 的数据值可能都共享相同的外部 id。
因此我的目标是更新其中的数据。我创建的表单元素如下所示:
$sql = "SELECT * FROM test.test WHERE externalId = $callID";
$r = mysqli_query($conn, $sql) or die(mysqli_error($conn));
for ($tcount =1; $rowTest = mysqli_fetch_assoc($rtest); $tcount++){
$idtest = $rowTicket['idtest'];
$testfieldA = $rowTicket['testfieldA'];
$testfieldB = $rowTicket['testfieldB'];
$testfieldC = $rowTicket['testfieldC'];
$externalid = $rowTicket['externalId'];
echo "<div>";
echo "<input type='hidden' name='idtest' value='$idtest'>";
echo "<input type='text' name='testfieldA[$tcount]' value='$testfieldA'>";
echo "<input type='number' step='0.01' min='0' name='testfieldB[$tcount]' value='$testfieldB'>";
echo "<input type='number' name='testfieldC[$tcount]' value='$testfieldC'>";
echo "<input type='hidden' name='externalId' value='$externalid'>";
echo "</div>";
}
这将回显带有 name=name[e] 的表单标记,例如返回数字的初始值。我也不为 idtest 执行 name=idtest[],因为无论如何它每次都是唯一的。
所有这些都工作得很好,并且当通过将其链接到 updatetest.php?callid=# 的 onclick 函数调用时,它会从数据中呼应我想要的内容。不过,我现在想更新一下内容。我正在尝试的系统是调用 while 循环,如下所示:
$e = 0;
$more = TRUE;
$idtest = $_POST['idtest'];
while($more){
if(isset($_POST['testfieldA'.$e]) && isset($_POST['testfieldB'.$e]) && isset($_POST['testfieldC'.$e])){
$test1 = $_POST['testfieldA'.$e];
$test1 = trim($test1);
$test2 = $_POST['testfieldB'.$e];
$test2 = trim($test2);
$test3 = $_POST['testfieldC'.$e];
$test3 = trim($test3);
$sql = "UPDATE test.test SET testfieldA = ?, testfieldB = ?, testfieldC= ? WHERE idtest = ?";
$stmt = mysqli_prepare($conn, $sql) or die(mysqli_error($conn));
mysqli_stmt_bind_param($stmt, "sssd", $test1, $test2, $test3, $idtest) or die(mysqli_error($conn));
mysqli_stmt_execute($stmt) or die(mysqli_error($conn));
mysqli_stmt_close($stmt);
} else {
$more = FALSE;
}
}
$e++;
但是,这不会运行。循环遍历每个名称并获取号码并在名称存在时更新数据的有效方式是什么?顺便说一句,如果这个问题看起来不清楚,我很难表达它。
最佳答案
在 HTML 表单中以这种方式写入输入:
echo "<input type='text' name='testfield1[]' value='$testfield1'>";
提交表单直接进行数组转换。
然后,处理数据,写成这样:
for( $i = 0; $i < count( $_POST['testfield1'] ); $i++ )
{
$test1 = trim( $_POST['testfield1'][$i] );
$test2 = trim( $_POST['testfield2'][$i] );
(...)
}
关于php - 通过从名称数组获取值来更新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36485861/