Postgres/PHP PDO::PDOStatement->bindParam() 到字符(1) 字段
我有类似于以下内容的代码:
$data['someField'] = (isset($_POST['someField'])) ? 'Y' : 'N';
$stmt = $db->prepare("INSERT INTO public.someTable (someField) VALUES (':someField');");
$stmt->bindParam(':someField', ($data['someField']), PDO::PARAM_STR, 1);
$db->beginTransaction();
$stmt->execute();
$db->commit();
该字段是一个包含 Y 或 N 的字符(1)(我宁愿使用 bool/int(1),但不幸的是我无法更改)。正如您所看到的,这从 HTML 表单中获取 POST 数据,并根据复选框设置 Y 或 N。当我回显时,该变量看起来设置正确。如果我手动将“Y”或“N”放入语句中,查询就会起作用,但是当使用bindParam()时,我会收到以下错误:
SQLSTATE[22001]: String data, right truncated: 7 ERROR: value too long for type character(1)
真正奇怪的是,即使我做了这样的事情:
$stmt->bindParam(':someField', substr($data['someField'], -1), PDO::PARAM_STR, 1);
我仍然收到错误。来自 php.net 功能页面的用户评论:
Steve M 2009 年 11 月 19 日 07:28 请注意 当使用 PDOStatement::bindParam 时 整数更改为字符串值 基于 PDOStatement::execute()。 (已测试 与 MySQL)。
没有进一步提及这一点,也没有任何关于如何解决它的内容。我假设这是问题的根源。我也尝试过使用bindValue(),没有任何改变。
I have code similar to the following:
$data['someField'] = (isset($_POST['someField'])) ? 'Y' : 'N';
$stmt = $db->prepare("INSERT INTO public.someTable (someField) VALUES (':someField');");
$stmt->bindParam(':someField', ($data['someField']), PDO::PARAM_STR, 1);
$db->beginTransaction();
$stmt->execute();
$db->commit();
The field is a character(1) that contains either a Y or N (I'd rather use a bool/int(1), but I can't change that unfortunately). As you can see, this takes the POST data from an HTML form and set Y or N based on a checkbox. The variable looks properly set when I echo it. The query works if I manually put a 'Y' or 'N' into the statement, but when using bindParam() I get the following error:
SQLSTATE[22001]: String data, right truncated: 7 ERROR: value too long for type character(1)
The really odd thing is even if I do something like this:
$stmt->bindParam(':someField', substr($data['someField'], -1), PDO::PARAM_STR, 1);
I still get the error. From the user comments on the function page at php.net:
Steve M 19-Nov-2009 07:28 Note that
when using PDOStatement::bindParam an
integer is changed to a string value
upon PDOStatement::execute(). (Tested
with MySQL).
There is no further mention of this, or anything on how to get around it. I am assuming that this the root of the problem. I have also tried using bindValue() with no change.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这里找到了这个问题的答案:PdoStatement->bindParam() 上的字符串编码问题? 一旦
基本上 PDO 会自动为你转义参数,所以当我进行查询时:
PDO 完成它,它最终看起来像这样:
正确使用prepare() 函数是:
Found the answer for this problem here: String encoding problem on PdoStatement->bindParam()?
Basically PDO will automatically escape the parameter for you, so when I made my query:
Once PDO was done with it it ended up looking like this:
Correct use of the prepare() function is: