简体   繁体   English

将数组提取到动态变量中

[英]Extracting an array into dynamic variables

I am trying to be lazy (or smart): I have 7 checkboxes which correlate with 7 columns in a MySQL table. 我试图变得懒惰(或聪明):我有7个复选框,与MySQL表中的7列相关联。

The checkboxes are posted in an array: 复选框发布在一个数组中:

$can = $_POST['can'];

I've created the following loop to dump the variables for the MySQL insert: 我创建了以下循环来转储MySQL插入的变量:

for($i=1;$i<8;$i++){
    if($can[$i] == "on"){
        ${"jto_can".$i} = 'Y';
    }
    else{
        ${"jto_can".$i} = 'N';
    }
}
print_r($jto_can1.$jto_can2.$jto_can3.$jto_can4.$jto_can5.$jto_can6.$jto_can7);

This correctly outputs: 这正确输出:

YYNYYYY

However, when I attempt to use those variables in my MySQL update, it doesn't accept the changes. 但是,当我尝试在MySQL更新中使用这些变量时,它不接受更改。

mysqli_query($db, "UPDATE jto SET jto_can1 = '$jto_can1', jto_can2 = '$jto_can2', jto_can3 = '$jto_can3', jto_can4 = '$jto_can4', jto_can5 = '$jto_can5', jto_can6 = '$jto_can6', jto_can7 = '$jto_can7' WHERE jto_id = '$id'")or die(mysqli_error($db));

Can anyone explain why the print_r displays the variables whereas MySQL update does not? 任何人都可以解释为什么print_r显示变量而MySQL更新不显示?

Stick with the array, and form the query dynamically: 坚持使用数组,并动态地形成查询:

$sql = 'UPDATE jto SET ';

$cols = array();
foreach( range( 1, 7) as $i) {
    $value = $_POST['can'][$i] == 'on' ? 'Y' : 'N'; // Error check here, $_POST['can'] might not exist or be an array
    $cols[] = 'jto_can' . $i . ' = "' . $value . '"'; 
}

$sql .= implode( ', ', $cols) . ' WHERE jto_id = "' . $id . '"';

Now do a var_dump( $sql); 现在做一个var_dump( $sql); to see your new SQL statement. 查看新的SQL语句。

this is not a mysql problem. 这不是一个mysql问题。 mysql will only see what you put into that string. mysql只会看到你放入该字符串的内容。 eg dump out the query string BEFORE you do mysql_query. 例如,在执行mysql_query之前转储查询字符串。 I'm guessing you're doing this query somewhere else and have run into scoping problems. 我猜你在其他地方做了这个查询,并且遇到了范围问题。 And yes, this is lazy. 是的,这很懒惰。 No it's not "smart". 不,它不“聪明”。 you're just making MORE work for yourself. 你只是为自己做更多工作。 What's wrong with doing 这样做有什么问题

INSERT ... VALUES jto_can1=$can[0], jto_can2=$can[1], etc...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM