选择一行的随机FIELD并相应地更新它


Select a random FIELD of a row and update it accordingly

我需要构建一个函数,选择字段的随机行,但不是任何行。

假设字段名为

id, user, one, two, three, four,five,six
1,'jack',0,0,0,1,0,0

当函数被调用时,我需要更新以下字段之一:one, two, three, four,five,six的值为'0',并将其设置为'1'。因此,一个字段不能被多次选中。在现实中,有超过10个领域需要这种处理。顺序必须是随机的

我还在试着在不写太多行的情况下找出逻辑。有什么建议吗?

如何:

    function Z($id){
    $array =array('one','two','three'); //field names
     shuffle($array);//radnoise the array
     $update='';
     foreach($array as $k => $a){
        if($k==0){
            $update .="'$a'=1,";//first random field is 1
        }else{
            $update .="'$a'=0,";//all other fields are 0
        }
    }
    $update=rtrim($update,",");//remove last comma
    $q="update table set $update where id=$id";
return $q; //for testing, otherwise run query
}
echo Z('4'); //test it

//

版本2
function ZZ($id){
    $array =array('one','two','three'); //field names
     $value=$array[array_rand($array)];
    $q="update table set '$value'=1 where id=$id";
return $q; //for testing, otherwise run query
}
echo ZZ('4'); //test it

我从来没有听说过在任何数据库中选择随机列的方法,但是如果值都是1或0,为什么不把它们都放入一个呢?这样你就会得到一个像101000100001001这样的字符串,其中每个数字代表一个不同的"列"。您可以使用PHP来操作它并更新数据库