几年前,我学习了PHP课程,但是大多数知识已经消失了。所以我有一个问题。在Joomla表单(RSJoomla的RSForms)中,我使用的是这样的重复代码:
$locatie01 = $_POST['form']['locatie_01'];
$locatie02 = $_POST['form']['locatie_02'];
$locatie03 = $_POST['form']['locatie_03'];
$locatie04 = $_POST['form']['locatie_04'];
$locatie05 = $_POST['form']['locatie_05'];
$locatie06 = $_POST['form']['locatie_06'];
并且一直持续到达到100。(位置(荷兰语中拼写为“ locatie”)被发布到数据库中。再往下一点,我们正在做类似的事情,但是要编写更复杂的代码,所以我只列出3:
$db->setQuery("
INSERT INTO #__instellingen
(type,instelling,locatie,contactpersoon,telefoon,email,ivvu,vgu,token)
VALUES
('".$type."','".$instelling."','".$locatie01."','".$contactpersoon."','".$telefoon."','".$email."','".$ivvu."','".$vgu."','".$token."')
");
$db->query();
if(!empty($locatie02)){
$db->setQuery("
INSERT INTO #__instellingen
(type,instelling,locatie,contactpersoon,telefoon,email,ivvu,vgu,token)
VALUES
('".$type."','".$instelling."','".$locatie02."','".$contactpersoon."','".$telefoon."','".$email."','".$ivvu."','".$vgu."','".$token."')
");
$db->query();
}
if(!empty($locatie03)){
$db->setQuery("
INSERT INTO #__instellingen
(type,instelling,locatie,contactpersoon,telefoon,email,ivvu,vgu,token)
VALUES
('".$type."','".$instelling."','".$locatie03."','".$contactpersoon."','".$telefoon."','".$email."','".$ivvu."','".$vgu."','".$token."')
");
$db->query();
}
而且还会继续到100
[我们在这里所做的是:第一行总是被填充(必填字段,然后从此开始:如果2不为空,则将数据发送到数据库,与3相同,等等。
现在我可以说这不是最短的编码方式,我隐约记得我们能够编写较短的代码;附带编码吗?如果...。对不起,我不记得了。...谁能刷新我的记忆?
Thanx,
汤姆
由于每个元素的查询都相同,因此您可以执行以下操作。同样,也不需要检查它是否存在,因为您将只处理数组中的值。您需要使用准备好的语句并在此处进行清理,不要将原始表单数据插入数据库。
foreach($_POST['form'] as $key => $locatie) {
$db->setQuery("
INSERT INTO #__instellingen
(type,instelling,locatie,contactpersoon,telefoon,email,ivvu,vgu,token)
VALUES ('".$type."','".$instelling."','".$locatie."','".$contactpersoon."','".$telefoon."','".$email."','".$ivvu."','".$vgu."','".$token."')
");
}
您的代码不完整,我不知道$token
变量来自哪里,所以我假设它来自表单。另外,我猜对于DB,您正在使用PDO
对象,但对于mysqli
驱动程序,它几乎是相同的。
您可以执行类似的操作:
foreach($_POST['form'] as $key) {
$sql = 'INSERT INTO #__instellingen (type, instelling, locatie,
contactpersoon, telefoon, email, ivvu, vgu, token) VALUES (?,?,?,?,?,?,?,?,?)';
$stmt = $pdo->prepare($sql);
$stmt->execute([$key['type'], $key['instelling'], $key['locatie'], $key['contactpersoon'], $key['telefoon'],
$key['email'], $key['ivvu'], $key['vgu'], $key['token']);
}
[?平均绑定参数。使用预处理语句来添加一层以避免在代码中进行SQL注入很重要。