有没有办法把这些if语句写得短一点?
if($data==name){
$sql1 = "UPDATE people set firstname = ? WHERE id = '$id'";
$q = $pdo->prepare($sql1);
$q->execute(array($name));
}
if($data==age){
$sql2 = "UPDATE people set age = ? WHERE id = '$id'";
$q = $pdo->prepare($sql2);
$q->execute(array($age));
}
if($data==color1){
$sql3 = "UPDATE people set paint1 = ? WHERE id = '$id'";
$q = $pdo->prepare($sql3);
$q->execute(array($color));
}
if($data==color2){
$sql4 = "UPDATE people set paint2 = ? WHERE id = '$id'";
$q = $pdo->prepare($sql4);
$q->execute(array($color));
}
if($data==color3){
$sql5 = "UPDATE people set paint3 = ? WHERE id = '$id'";
$q = $pdo->prepare($sql5);
$q->execute(array($color));
}
我试着做一个函数
function data($info, $information, $name){
if($data==$info){
$sql = "UPDATE people set $information = ? WHERE id = '$id'";
$q = $pdo->prepare($sql);
$q->execute(array($name));
}
}
data(name, firstname, $name);
但不是这样的,我没有结果。可能是因为sql请求中的变量?
最佳答案
<?php
switch($data){
case "name":
$field = "firstName";
break;
case "age":
$field = "age";
break;
case "color1":
$field = "paint1";
break;
case "color2":
$field = "paint2";
break;
case "color3":
$field = "paint3";
break;
default:
echo 'Invalid selection';
exit;
break;
}
$sql = "UPDATE people set $field = ? WHERE id = '$id'";
$q = $pdo->prepare($sql);
$q->execute(array($name));
关于php - 如何用较短的方式编写很多类似的if语句?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37827991/