我是PHP函数的新手。我认为可以使用函数解决以下问题。在这里,我能够将html表单数据存储在数据库中,该数据库使用以下代码从ajax传递。但我有点困惑,如果条件实施的地方。如果已提交数据,我想停止数据复制。
我正在使用的PHP代码
if(isset($_POST["section_name"])){
$section_name = $_POST["section_name"];
$class_id = $_POST["class_id"];
for($count = 0; $count<count($section_name); $count++)
{
$query =$con->prepare('INSERT INTO section(class_id, section_name) VALUES (:class_id, :section_name)');
$query->bindParam(':class_id', $class_id);
$query->bindParam(':section_name', $section_name[$count]);
$query->execute();
echo "Section has been assigned";
}
}
现在,我希望将以上代码包含在其他条件中。
$query =$con->query('SELECT * FROM section');
while($row=$query->fetch(PDO::FETCH_ASSOC)){
if(($_POST["class_id"]==$row["class_id"])&&($_POST["section_name"]==$row["section_name"])){
echo "Section has already assigned in this class ";
}
else{
// insert...
}
}
当我尝试合并代码时,我无法处理。请帮帮我
答案 0 :(得分:1)
你几乎拥有所有东西,你只需要将它包装在这样的函数中:
function insert() {
if(isset($_POST["section_name"])){
$section_name = $_POST["section_name"];
$class_id = $_POST["class_id"];
for($count = 0; $count<count($section_name); $count++)
{
$query =$con->prepare('INSERT INTO section(class_id, section_name) VALUES (:class_id, :section_name)');
$query->bindParam(':class_id', $class_id);
$query->bindParam(':section_name', $section_name[$count]);
$query->execute();
echo "Section has been assigned";
}
}
}
然后你这样称呼它:
$query =$con->query('SELECT * FROM section');
while($row=$query->fetch(PDO::FETCH_ASSOC)){
if(($_POST["class_id"]==$row["class_id"])&&($_POST["section_name"]==$row["section_name"])){
echo "Section has already assigned in this class ";
}
else{
insert();
}
}