7

我正在使用 Wordpress 中的 WPDB 对象与 MySQL 数据库进行通信。我的数据库有一个类型为 的列bit(1),但是,Wordpress 不会在我的生产服务器上将它们提取为01(它们是在我的本地计算机上提取的)。


问题:

如果我有来自 Wordpress 的数据库值,我无法与0or进行简单的比较1

if ($data[0]->Sold == 1) { //Always false
...
if ($data[0]->Sold == 0) { //Always false

如何检查该值是否01


背景:

这在我的本地机器上不是问题,而只是在生产中。

我这样查询数据库:

$data = $wpdb->get_results("...");

当我var_dump()对数据库的结果执行操作时,这是我的浏览器显示的输出:

array(1) {
  [0] => object(stdClass)#261 (10) {
    ["SaleID"]     => string(4) "1561"
    ["BookID"]     => string(2) "45"
    ["MerchantID"] => string(1) "1"
    ["Upload"]     => string(19) "2012-11-20 15:46:15"
    ["Sold"]       => string(1) ""
    ["Price"]      => string(1) "5"
    ["Condition"]  => string(1) "5"
    ["Written"]    => string(1) ""
    ["Comments"]   => string(179) "<p>I am the first owner of this barely used book. There aren't any signs of normal wear and tear, not even any creases on the cover or any of its pages. It would pass for new.</p>"
    ["Expiring"]   => string(19) "2013-05-20 15:46:15"
  }
}

注意如何显示字符串大小Sold,但没有关联的值。这些值应分别用和填充。Written110

Chrome 检查器工具对这些值显示了一些非常有趣的东西:

在此处输入图像描述

在此处输入图像描述

什么是\u1or \u0,为什么它们不是简单的1or 0,所以我可以进行比较?

感谢您的时间。

4

2 回答 2

1

检查这个答案: https ://stackoverflow.com/a/5323169/794897

“当您使用 PHP 从 MySQL 数据库中选择数据时,数据类型将始终转换为字符串。”

你可以这样做:

if ($data[0]->Sold === "1") { 
...
if ($data[0]->Sold === "0") { 

或类型转换变量,例如

$Sold = (int) $data[0]->Sold;

if ($Sold === 1) { 
...
if ($Sold === 0) { 
于 2013-09-03T12:02:18.830 回答
0

对我来说,解决方案是使用 ord 函数:http ://us1.php.net/manual/en/function.ord.php

编辑

然而,行为似乎因服务器而异。在带有 MariaDB 10.0.14 的 Arch Linux 和带有 MySQL 5.5.37-0ubuntu0.13.10.1 的 Ubuntu 上,wpdb返回良好的旧“0”或“1”字符串,而不是在 CentOS 6.4 MySQL 5.1.73 上发生的有问题的位字符串

于 2014-11-21T12:18:22.410 回答