【发布时间】:2011-07-19 08:00:12
【问题描述】:
我有以下有效的代码,但它没有使用我通常使用的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>
但它给了我以下错误:
[2011 年 7 月 19 日星期二 09:15:44] [错误] [客户端 ::1] PHP 致命错误: 带有消息“SQLSTATE [42000]”的未捕获异常“PDOException”: 语法错误或访问冲突:1064 您的 SQL 中有错误 句法;检查与您的 MySQL 服务器版本相对应的手册 在 '' db_field1=0, dbfield2=1, 附近使用正确的语法 dbfield3=1, dbfield4=0' where id = 1' at line 1' in /var/www/page1.php:30\n堆栈跟踪:\n#0 /var/www/page1.php(30): PDOStatement->execute()\n#1 {main}\n 在第 30 行的 /var/www/page1.php 中抛出, 引用者:http://localhost/page1.php
【问题讨论】:
-
试试并发布你的结果?
-
我试过了。请查看我得到的错误。
-
所以调试一下,是语法错误。输出你的查询,找出你的错误。