mercredi 15 juin 2016

How can I write a lot of similar if-statements in a shorter way?

Is there a way to write this bunch of if statements shorter?

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));
}

I tried to make a function

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);

But it is not working like this, I do not get a result. Maybe because of the variable inside the sql request?

Aucun commentaire:

Enregistrer un commentaire