简体   繁体   English

PDO & MS SQL 服务器:为 integer 列插入值导致错误

[英]PDO & MS SQL Server: inserting value for integer column results in error

I am trying to insert an integer value into my INT column.我正在尝试将 integer 值插入到我的 INT 列中。 However, when I execute the following PHP-code, it results in an error telling me that I am trying to insert a "text", which should not be the case...但是,当我执行以下 PHP 代码时,它会导致错误告诉我我正在尝试插入“文本”,但事实并非如此......

PHP PHP

$myCode = 1;
$sth = $db->prepare("INSERT INTO tblCodes (myCode) VALUES (:myCode)");
$sth->bindParam(':myCode', $myCode, PDO::PARAM_INT);
$sth->execute();

Error错误

SQLSTATE[22018]: Invalid character value for cast specification: 206 [FreeTDS][SQL Server]Operand type clash: text is incompatible with int (SQLExecute[206] at /builddir/build/BUILD/php-5.6.9/ext/pdo_odbc/odbc_stmt.c:254) SQLSTATE[22018]:转换规范的无效字符值:206 [FreeTDS][SQL Server]操作数类型冲突:文本与 int 不兼容(SQLExecute[206] 在 /builddir/build/BUILD/php-5.6.9/ext/ pdo_odbc/odbc_stmt.c:254)

Can anybody help me?有谁能够帮我? Thanks a lot!非常感谢!

Such a situation may appear if the user to whom you connect to the database does not have the appropriate permissions.如果您连接到数据库的用户没有适当的权限,则可能会出现这种情况。

A moment ago I had a similar problem with the scalar function. It turned out that adding execute permissions to the user solved the problem.刚才遇到了标量function的类似问题,原来给用户加上执行权限就解决了。 Without permission, it seems to me that the driver is unable to determine the data types, and by default it assumes it is text.未经许可,在我看来,驱动程序无法确定数据类型,默认情况下它假定它是文本。

I think that it is a bug. 我认为这是一个错误。 I solved my problem by change in the query. 我通过更改查询解决了我的问题。 In your case change the query as below: 根据您的情况,更改查询,如下所示:

$myCode = 1;
$sth = $db->prepare("INSERT INTO tblCodes (myCode) VALUES (CAST(CAST(:myCode AS varchar) AS INTEGER))");
$sth->bindParam(':myCode', $myCode, PDO::PARAM_INT);
$sth->execute();

Now it should be worked by both PDO::PARAM_INT and PDO::PARAM_STR . 现在,它应该同时由PDO::PARAM_INTPDO::PARAM_STR

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM