php - 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 = ?;";
}
.....
解决方案
不要像这样存储数据。这只是在问问题。而是规范化您的架构并以关系方式存储数据。
如果您坚持当前的设计,您可以通过动态构建 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 = ?;";
}
推荐阅读
- css - 使用 CSS 动画关闭 SVG 框的盖子
- javascript - ThreeJS 和 Typescript:如何跟踪或勾勒对象旋转的路径?
- mongodb - 在本地托管 mongoDB 数据库,并能够从外部网络连接
- python - 尝试计算 dask 数据帧时出错
- python - Python - 是否有为提取的 .DOC 文件创建标题?
- android - Android Studio - 文件系统同步
- python - 将pyspark中的数据帧编码为0和1
- java - Java - ExecutorService 在一段时间后停止处理线程
- bpf - 使用 uBPF 打印 Hello World?
- typescript - 基于请求/响应的 rxjs WebSocketSubject 的不同类型(下一个 msg 类型,订阅 msg 类型),但只允许一个泛型