如何仅通过Key =>更新设置表值

时间:2018-04-07 12:27:46

标签: php mysql pdo

我有一个以下列方式构建的设置表(为了简单起见,我在这里保留代码简短):

 ID |   key  |  value  |  category
-----------------------------------------
1   |  key_a | value_a |  geolocal
2   |  key_b | value_b |  geolocal
3   |  key_c | value_c |  geolocal
4   |  key_d | value_d |  opengraph
5   |  key_e | value_e |  opengraph

我通过php / html页面阅读此表,目的是为了能够更新上述设置

<?
require_once $_SERVER['DOCUMENT_ROOT'].'include/setup.php';

if (!empty($_POST['submit']) and $_POST['submit'] == "UPDATE") {
    ...
    ... I EXPLAIN THIS CODE, WHICH SHOULD WORK ONLY WHEN "SUBMIT" IS CLICKED, BELOW.
    ...

}

$query = "SELECT * FROM setup";
$sth = sql->prepare($query);
$sth->execute;

while($row = $sth->fetch(PDO::FETCH_ASSOC)){
    ${$row[$param]} = $row[$value];
?>
...
...
...
<div id="tabs-1">
    <form method="POST">
        <div class="tab">
            <p><label for="key_a">KEY 1</label><input name="key_a" value="<? echo $key_a; ?>" size="50"/></p>
            <p><label for="key_b">KEY 2</label><input name="key_b" value="<? echo $key_b; ?>" size="50"/></p>
            <p><label for="key_c">KEY 3</label><input name="key_c" value="<? echo $key_c; ?>" size="50"/></p>
            <p><label for="key_d">KEY 4</label><input name="key_d" value="<? echo $key_d; ?>" size="50"/></p>
        </div>
        <input type="submit" name="submit" value="UPDATE"><input type="reset" value="RESET">
    </form>
</div>
...
...
...
<?
} // END While
?>

key_a,key_b等只是示例。 在现实中,被称为:

app_secret
artist_name
token_page_access
etc etc ...

因此,当我更新值时,我必须为每个条目(我上面提到的代码)创建以下查询:

$query="UPDATE setup SET value = $_POST['key_a'] WHERE key = key_a";
$query="UPDATE setup SET value = $_POST['key_b'] WHERE key = key_b";
$query="UPDATE setup SET value = $_POST['key_c'] WHERE key = key_c";
$query="UPDATE setup SET value = $_POST['key_d'] WHERE key = key_d";

正如我所说,我在这张桌子上不仅有4个值,而且差不多有150个。

有没有办法简化UPDATE查询,以便简化代码并提高效率?

1 个答案:

答案 0 :(得分:2)

鉴于当前情况,您应该遍历$_POST超全局数组来执行UPDATE操作,如下所示:

if (!empty($_POST['submit']) and $_POST['submit'] == "UPDATE") {
    $query = "UPDATE `setup` SET `value` = :value WHERE `key` = :key";
    $sth = $sql->prepare($query);
    foreach($_POST as $key => $value){
        if($key != 'submit'){
            $sth->execute(array(':value'=>$_POST[$key], ':key'=>$key));
        }
    }
}

旁注: key是保留字,value是MySQL中的关键字。你应该总是用反引号封装你的表名和列名,只是为了安全起见。 Keywords and Reserved Words in MySQL