php - BindValue 不接受假值

标签 php mysql pdo

我在数据库中有一个文本数据类型,想要输入 true 或 false 值。如果我使用带有 BindParam 的 Mysqli 或 PDO 可以正常工作,它会添加 1 或 0,但是当我尝试使用 BindValue 时,它​​只能正常工作。错误值被替换为空白。

empty values

try{
 $conn =  new PDO("mysql:host=localhost;dbname=name_db", "root", "");
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

 $sql = "INSERT INTO upload_meta (video_id, upload_key, upload_value) VALUES (:video_id,:upload_key,:upload_value)"; 
 $temp = $conn->prepare($sql);
 $temp->bindValue(':video_id', 11111111);
 $temp->bindValue(':upload_key', 'exodo');
 $temp->bindValue(':upload_value', false);

$temp->execute();   

}catch(PDOException $e){

    echo $e->getMessage();


}

该字段将接收需要为文本的各种类型的值。

CREATE TABLE `upload_meta` (
  `meta_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `video_id` int(11) unsigned NOT NULL,
  `upload_key` varchar(255) DEFAULT NULL,
  `upload_value` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`meta_id`),
  KEY `video_id` (`video_id`),
  KEY `index_upload_key` (`upload_key`(191)),
  CONSTRAINT `upload_meta_ibfk_1` FOREIGN KEY (`video_id`) REFERENCES `video` (`id_video`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

最佳答案

根据文档

答案在 bindParam 的文档中:

Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

execute

call PDOStatement::bindParam() to bind PHP variables to the parameter markers: bound variables pass their value as input and receive the output value, if any, of their associated parameter markers

您的案例

您的数据库结构需要 upload_value 为 varchar,它基本上是文本/字符串。当您使用 bindParam 时,它正在工作,因为它传递的是 true 或 false 值,即 1 或 0

但是当您使用bindValue时,引用将被传递,然后在执行时进行评估,因此 true 被转换为 1(字符串/文本),但 false 被评估为“空”字符串。

解决方案

要么使用bindParam,要么如果您想使用bindValue,您应该更新数据库结构以接受upload_value的 bool 值而不是varchar

5 分钟指南:https://w3guy.com/php-pdostatement-bindparam-bindvalue/

关于php - BindValue 不接受假值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54089493/

相关文章:

mysql - MySQL 可以为单个查询使用多个索引吗?

Java Hibernate sqlGroupProjection mysql 语法错误

mysql - 统计每件售出的产品

PHP PDO 未在我的网页上显示任何数据

php - 处理失败的 nonce 验证的最佳方法是什么?

php - echo 在 php join 中具有相同名称的变量

php - 函数 __construct 上的数据库参数

php - PDO 中的开始事务

javascript - Zend Framework 2 中根据请求类型在同一路由上触发不同的操作

php - 仅在需要时自动连接到 PDO