I have the following code which works, but it’s not using PDO which is what I normally use:
<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
// will go all the way upto 50
$fields = array('db_field1'=>'cb1', 'dbfield2'=>'cb2', 'dbfield3'=>'cb3', 'dbfield4'=>'cb4');
$update = '';
foreach($fields as $dbfield => $field) {
if ($update) $update.= ',';
$update.= ' '.$dbfield.'=';
if (isset($_POST[$field])) {
$update.= 1;
} else {
$update.= 0;
}
}
// show generated query
echo 'UDPATE table SET'.$update.' WHERE 1=1';
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="post">
<input type="checkbox" name="cb1" />
<input type="checkbox" name="cb2" />
<input type="checkbox" name="cb3" />
<input type="checkbox" name="cb4" />
<!-- all the way to 50 -->
<input type="submit" value="submit" />
</form>
</body>
</html>
Because I am getting the column names AND the column values to be updated from the code above, I am not sure how to do this using PDO?
I have done the following code below:
<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$fields = array('db_field1'=>'cb1', 'dbfield2'=>'cb2', 'dbfield3'=>'cb3', 'dbfield4'=>'cb4');
$update = '';
foreach($fields as $dbfield => $field) {
if ($update) $update.= ',';
$update.= ' '.$dbfield.'=';
if (isset($_POST[$field])) {
$update.= 1;
} else {
$update.= 0;
}
}
$DBH = new PDO( "mysql:host=localhost;dbname=database", "user", "pass" );
$DBH -> setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $DBH -> prepare( "update table1 set :update where id = :id" );
$STH -> bindParam( ':update', $update, PDO::PARAM_STR, 255 );
$STH -> bindParam( ':id', $id, PDO::PARAM_INT, 4 );
$STH -> execute();
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="post">
<input type="checkbox" name="cb1" />
<input type="checkbox" name="cb2" />
<input type="checkbox" name="cb3" />
<input type="checkbox" name="cb4" />
<!-- all the way to 50 -->
<input type="submit" value="submit" />
</form>
</body>
</html>
But it gives me the following error:
[Tue Jul 19 09:15:44 2011] [error] [client ::1] PHP Fatal error:
Uncaught exception ‘PDOException’ with message ‘SQLSTATE[42000]:
Syntax error or access violation: 1064 You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near ” db_field1=0, dbfield2=1,
dbfield3=1, dbfield4=0′ where id = 1′ at line 1’ in
/var/www/page1.php:30\nStack trace:\n#0
/var/www/page1.php(30): PDOStatement->execute()\n#1
{main}\n thrown in /var/www/page1.php on line 30,
referer: http:// localhost/page1.php
Use:
instead of:
Or you can use this:
instead of: