这在php网页中
我有一个链接作为www.example.com/add_new.php?code=1234[]&code=4321[]&code=4263[]&attend=1
输入。我需要更新数据库,以便将code
标记为attend="1"
。如果我只有一个,我可以让它工作。但是,当我有多个值时,我可以循环使用它来编辑所有值吗?
$codes = $_GET['code'];
foreach ($codes as $code) {
$sql = "UPDATE guests SET attend='$isattend' WHERE code=$add";
}
正确的语法是什么?
现在它只在code=4263[]
上应用最后一个,并标记4263 as attend=1
,但我需要foreach
谢谢。
使用类似?code=1234&code=4321&code=4263&attend=1
的查询字符串,您的code
值将为4263
。原因以前的值被以下内容覆盖。要在查询字符串中传递多个代码,应使用[]
:
?code[]=1234&code[]=4321&code[]=4263&attend=1
然后在$_GET['code']
中,您将有一个数组:
$codes = $_GET['code'];
// also you can check if $codes is array with `is_array` function
foreach ($codes as $code) {
// do some database related stuff
$sql = "UPDATE guests SET attend='$isattend' WHERE code=$add";
}
你走在了正确的轨道上。如果您有一个要更新的项数组,那么您可以循环遍历它们并执行更新查询。你的回答中有很多东西让我觉得你应该退后一步,复习一下基本知识。
首先,foreach循环看起来像这样:
foreach ($items as $item) {
//do something
}
接下来,您真的不想像现在这样编写SQL查询。这是个坏主意,因为人们可以利用你的代码并通过SQL注入攻击你
为了防止这种情况,您可以使用PHP附带的一个名为PDO的库:http://php.net/manual/en/book.pdo.php
您将使用一种称为prepared语句的东西,它可以让您设计SQL查询,然后向其中注入值,这有助于防止所有可怕的注入攻击。例如,你的可能看起来像
$stmt = $pdo->prepare("UPDATE guests SET attend=:attend WHERE code=:code");
$stmt->bindParam(':attend', $attend);
$stmt->bindParam(':code', $code);
$stmt->execute();
我将由你来决定如何执行这个建议。祝你好运