Der*_*iel 4 php pdo prepared-statement
我刚刚开始准备语句的工作,我的第几个例子摸索出伟大的,但现在我运行到一个SQL语法,我不明白.我有一个执行INSERT的函数,带有一个关联数组的参数,其中数组的键是字段,数组的值是要插入的值.例如:
$arr = array("field1" => "value1",
"field2" => "value2");
$this->insert("table", $arr);
Run Code Online (Sandbox Code Playgroud)
会执行:
INSERT INTO table ('field1', 'field2') VALUES ('value1', 'value2')
Run Code Online (Sandbox Code Playgroud)
但是,在尝试执行此操作时,我收到以下错误:
PDOException:SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误; 检查与MySQL服务器版本对应的手册,以便在''post_title','post_body'附近使用正确的语法.)VALUES('Testing!','1 2 3!')'在第1行
这是我的功能:
/**
* insert()
*
* Performs an insert query
*
* @param string $table The table to be inserted into
* @param array $fields An associative array of the fields to be inserted
* and their respective values
* @return void
*
*/
function insert($table, $fields) {
if (empty($table) || empty($fields)) {
trigger_error('insert(): one or more missing parameters', E_USER_ERROR);
}
if (!is_array($fields)) {
trigger_error('insert(): second parameter expected to be array', E_USER_ERROR);
}
for ($i = 0; $i < count($fields); $i++) {
$mark[] = "?";
}
//(?, ?, ...)
$mark = "(" . implode(", ", $mark) . ")";
$bind = array_merge(array_keys($fields), array_values($fields));
//INSERT INTO table (?, ?, ...) VALUES (?, ?, ...)
$query = 'INSERT INTO '.$table.' '.$mark.' VALUES '.$mark;
//Prepare and execute
$stmt = $this->connection->prepare($query);
var_dump($stmt);
var_dump($bind);
$stmt->execute($bind);
}
Run Code Online (Sandbox Code Playgroud)
我打电话给:
$this->insert('post', array("post_title"=>"Testing!", "post_body"=>"1 2 3!"));
Run Code Online (Sandbox Code Playgroud)
最后两个var_dump()s导致:
object(PDOStatement)[7]
public 'queryString' => string 'INSERT INTO post (?, ?) VALUES (?, ?)' (length=37)
array
0 => string 'post_title' (length=10)
1 => string 'post_body' (length=9)
2 => string 'Testing!' (length=8)
3 => string '1 2 3!' (length=6)
Run Code Online (Sandbox Code Playgroud)
我可能错了,但据我所知,没有办法检查发送到服务器的实际查询,所以老实说我不知道SQL语法的来源.如果有人能指出可能出现的问题,我会非常感激.
您无法绑定标识符.所有志愿PDO布道者都不了解的事情.
您必须使用ol'good查询构建添加标识符.
将它们列入白名单并从该列表中创建字段名称子句
有关完整的实现,请参阅使用PDO插入/更新帮助程序功能.
| 归档时间: |
|
| 查看次数: |
1020 次 |
| 最近记录: |