I働き、次のコードを持っているが、私が通常使用するものであるPDO
を使用していない:パラメータ化されたPDOを使用して列と値を追加できますか?
<?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>
私は上記のコードから、更新するcolumn names
とcolumn values
を取得していますので、私はわかりませんどのようにPDO
を使用してこれを行うには?
私は下に次のコード実行した:
<?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>
をしかし、それは私に次のエラー与える:
[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
それを試してみて、あなたの結果を投稿? –
私はそれを試しました。私が得るエラーを見てください。 – oshirowanen
デバッグしてください。構文エラーです。あなたの質問を出力して、あなたのエラーを見つけてください。 –