Reputation: 17368
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:
What is \u1
or \u0
and why aren't they simply 1
or 0
, so I can do comparisons?
Thank you for your time.
Upvotes: 7
Views: 559
Reputation: 1376
For me the solution was to use ord function: https://www.php.net/manual/en/function.ord.php
Edit
Yet the behavior seems to differ depending on the server. On Arch Linux with MariaDB 10.0.14 and Ubuntu with MySQL 5.5.37-0ubuntu0.13.10.1 wpdb returns good old "0" or "1" strings, not the problematic bit-strings, which happen on CentOS 6.4 MySQL 5.1.73
Upvotes: 0
Reputation: 1106
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) {
Upvotes: 1