I have the following code, which almost works:
<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$fields = array(
'col1' => 'cb1',
'col2' => 'cb2',
'col3' => 'cb3',
'col4' => 'cb4',
'col5' => 'cb5',
'col6' => 'cb6',
'col7' => 'cb7',
'col8' => 'cb8',
'col9' => 'cb9',
'col10' => 'cb10'
);
$parts = array();
foreach( $fields as $dbfield => $field ) {
$parts[] = '`' . $dbfield . '` = :' . $dbfield;
}
$dbh = new PDO( 'mysql:host=localhost;dbname=database', 'user', 'pass' );
$dbh -> setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth = $dbh -> prepare( 'UPDATE `table1` SET ' . join( ', ', $parts ) . ' WHERE `id` = :id' );
// temp simulation value
$id = 1;
$sth -> bindParam( ':id', $id, PDO::PARAM_INT, 4 );
foreach( $fields as $dbfield => $field ) {
$value = isset( $_POST[$field] ) ? 1 : 0;
$sth -> bindParam( ':' . $dbfield, $value, PDO::PARAM_INT, 4 );
}
$sth -> execute();
$dbh = null;
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="post">
<input type="checkbox" name="cb1" /><br />
<input type="checkbox" name="cb2" /><br />
<input type="checkbox" name="cb3" /><br />
<input type="checkbox" name="cb4" /><br />
<input type="checkbox" name="cb5" /><br />
<input type="checkbox" name="cb6" /><br />
<input type="checkbox" name="cb7" /><br />
<input type="checkbox" name="cb8" /><br />
<input type="checkbox" name="cb9" /><br />
<input type="checkbox" name="cb10" />
<input type="submit" value="save" />
</form>
</body>
</html>
It should be inserting 0’s or 1’s depending on the checkbox selected, but for some reason it inserts 0’s into all columns no matter which checkboxes are selected. However, if the last checkbox is selected, it inserts a 1 into all columns.
bindParambinds the actual variable$value(by reference) which, by the time the loop ends, has a value based on$_POST['cb10']. (Recall that PHP has no block scope, so there is only one$valuevariable, as opposed to one for each loop iteration.)I think you meant to use
bindValue.Take a peek at the documentation: