Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress Database Class - MySQL Type Bit

I am using the WPDB object inside of Wordpress to communicate with a MySQL database. My database has a column with a type of bit(1), however, Wordpress does not extract these as a 0 or 1 on my production server (they did on my local machine).


Question:

If I have a database value from Wordpress, I can't do a simple comparison to 0 or 1:

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

How can I check if the value is 0 of 1?


Background:

This was not an issue on my local machine, but only in production.

I query the database like this:

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

When I do a var_dump() on the results from the database, here is the output my browser shows:

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"
  }
}

Notice how Sold and Written show a string size of 1, but don't have an associated value. These values should be populated with 1 and 0, respectively.

The Chrome inspector tool shows something quite interesting for these values:

enter image description here

enter image description here

What is \u1 or \u0 and why aren't they simply 1 or 0, so I can do comparisons?

Thank you for your time.

like image 391
Oliver Spryn Avatar asked Sep 02 '13 08:09

Oliver Spryn


1 Answers

Check this answer out: https://stackoverflow.com/a/5323169/794897

"When you select data from a MySQL database using PHP the datatype will always be converted to a string."

You can either do:

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

or type cast the variable, e.g.

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

if ($Sold === 1) { 
...
if ($Sold === 0) { 
like image 85
Elliot Lings Avatar answered Nov 05 '22 08:11

Elliot Lings