Fetching an array into dynamic variables

I'm trying to be lazy (or smart): I have 7 checkboxes that correlate with 7 columns in a MySQL table.

Flags are placed in an array:

$can = $_POST['can']; 

I created the following loop to dump variables for inserting 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 try to use these variables in my MySQL update, it does not accept the changes.

 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 someone explain why print_r displays variables while MySQL update is not working?

+4
source share
2 answers

Stick to the array and dynamically form the request:

 $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 var_dump( $sql); to see the new SQL statement.

+2
source

this is not mysql problem. mysql will only see what you put on this line. for example, unload the query string before you execute mysql_query. I assume that you are executing this request elsewhere and run into domain scoping issues. And yes, it's lazy. No, this is not smart. you are just doing GREAT work for yourself. What is wrong with work

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

All Articles