dongshu4755 2014-10-27 23:42
浏览 63
已采纳

在PDO中将列转换为布尔值

I have a field ('done') in the Database which is boolean. The function which GET/ the rows doesn't return a json with that field as boolean but it returns 1 or 0.

function getTasks() {
$sql = "SELECT id,task_name,done FROM tarea ORDER BY id";
try {
    $db = getConnection();
    $stmt = $db->query($sql);
    $tasks= $stmt->fetchAll(PDO::FETCH_OBJ);
    $db = null;
    echo json_encode($tasks);
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

How can I get THAT column ('done' column) as boolean? I mean, Is posible to cast a column with PDO::PARAM_BOOL ??

Here is my sample of UPDATE that inserts booleans in the database and it works perfectly:

function updateTask($id) {
$request = Slim::getInstance()->request();
$body = $request->getBody();
$task = json_decode($body);
$sql = "UPDATE tarea SET task_name=:task_name, done=:done WHERE id=:id";

try {
    $db = getConnection();
    $stmt = $db->prepare($sql);
    $stmt->bindParam("task_name", $task->task_name);

    $stmt->bindParam("done", $task->done,PDO::PARAM_BOOL);  // cast before execute

    $stmt->bindParam("id", $id);
    $stmt->execute();
    $db = null;
    echo json_encode($task);
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
  • 写回答

2条回答 默认 最新

  • dougourang1856 2014-10-28 00:35
    关注

    In SQL there are no booleans really, as you notice the 1 and 0 .

    The right terminology is BIT field. you should not try to modify it, if you retrieve it as 1 and 0 then you should insert it as 1 or 0.

    Also note that the JSON in the catch will produce is not valid, never build json manually. So change :

    echo '{"error":{"text":'. $e->getMessage() .'}}';
    

    to

    echo json_encode(array('error'=>$e->getMessage()));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀