首页 > 解决方案 > mysqli 更好的方法来改变使用什么列?

问题描述

所以我的代码需要有一个权重跟踪器,并且需要在一个数据点中至少保留 20 个权重。因为我不能用“?”动态改变它 这个位置我有 20 个 if () else if 语句能够做同样的事情。只是想知道是否有更好的方法来做到这一点,或者这是做到这一点的唯一方法?

代码开头:

function addWeight($conn, $location, $weight,$dt){
//select the two variables changing 
if($location == "Weight1"){
    $sql ="UPDATE userweight SET Weight1=? WHERE userId = ?;";
    $sql2 ="UPDATE userweight SET timee1=? WHERE userId = ?;";
}elseif($location == "Weight2"){
    $sql ="UPDATE userweight SET Weight2=? WHERE userId = ?;";
    $sql2 ="UPDATE userweight SET timee2=? WHERE userId = ?;";
}elseif($location == "Weight3"){
    $sql ="UPDATE userweight SET Weight3=? WHERE userId = ?;";
    $sql2 ="UPDATE userweight SET timee3=? WHERE userId = ?;";
}elseif($location == "Weight4"){
    $sql ="UPDATE userweight SET Weight4=? WHERE userId = ?;";
    $sql2 ="UPDATE userweight SET timee4=? WHERE userId = ?;";
}
.....

标签: phpmysqlmysqli

解决方案


不要像这样存储数据。这只是在问问题。而是规范化您的架构并以关系方式存储数据。

如果您坚持当前的设计,您可以通过动态构建 SQL 来克服这个问题。请务必使用硬编码的值列表验证列名是否正确。

function addWeight(mysqli $conn, $location, $weight, $dt)
{
    $columns = [
        "Weight1" => 'timee1',
        "Weight2" => 'timee2',
        "Weight3" => 'timee3',
        "Weight4" => 'timee4',
    ];
    if (!isset($columns[$location])) {
        throw new \RuntimeException("Invalid location");
    }
    $sql = "UPDATE userweight SET {$location}=? WHERE userId = ?;";
    $sql2 = "UPDATE userweight SET {$columns[$location]}=? WHERE userId = ?;";
}

推荐阅读