使用与PDO mysql相同的连接来处理多个if语句的有效方法

时间:2011-12-04 00:42:59

标签: php mysql pdo

我想问一下处理这些代码的有效方法是什么。即时检查表单中的更改,如果有更改,则存储到DB。有没有办法将4 if语句转换为一个。感谢

if ($_REQUEST['hidden_value_of_input_box1'] !== $newvalueofinputbox1) {    

    $data = "Input Box 1 has been changed";

    $name = $name;   
    $date = $datenow;    
    $stm = $dbh->prepare("INSERT INTO audit SET name=:name, datenow=:datenow, data=:data");     
    $stm->bindParam(':name', $name);   $stm->bindParam(':value', $value);   
    $stm->execute(); 
}  

if ($_REQUEST['hidden_value_of_input_box2'] !== $newvalueofinputbox2) {    

    $data = "Input Box 2 has been changed";

    $name = $name;   
    $date = $datenow;    
    $stm = $dbh->prepare("INSERT INTO audit SET name=:name, datenow=:datenow, data=:data");     
    $stm->bindParam(':name', $name);   $stm->bindParam(':value', $value);   $stm->execute(); 
}  

if ($_REQUEST['hidden_value_of_dropdown1'] !== $newvalueofdropdown1) {    

    $data = "Drop Down 1 has been changed";    

    $name = $name;   
    $date = $datenow;    
    $stm = $dbh->prepare("INSERT INTO audit SET name=:name, datenow=:datenow, data=:data");     
    $stm->bindParam(':name', $name);   $stm->bindParam(':value', $value);   $stm->execute(); 
}  

if ($_REQUEST['hidden_value_of_dropdown2'] !== $newvalueofdropdown2) {    

    $data = "Drop Down 2 has been changed";   

    $name = $name;   
    $date = $datenow;    
    $stm = $dbh->prepare("INSERT INTO audit SET name=:name, datenow=:datenow, data=:data");     
    $stm->bindParam(':name', $name);   
    $stm->bindParam(':value', $value);   
    $stm->execute(); 
} 

2 个答案:

答案 0 :(得分:0)

将输入字段作为数组返回,然后循环这些值,然后以这种方式,您的代码将更短,更简单,更动态。 :)

答案 1 :(得分:0)

在表格上:

<input name="hidden_value_of_input_box[]" type="hidden" value="anyvalue">
<input name="hidden_value_of_input_box[]" type="hidden" value="anyvalue">
<input name="hidden_value_of_input_box[]" type="hidden" value="anyvalue">

提交和处理:

<?php
foreach($_POST["hidden_value_of_input_box"] as $value){
echo $value;
}
?>
这样的事情。 :)