Return true when query gives 1 - mysql

I want to save a true/false in my MySQL database. I'm saving 1/0 in an INT column to do this. When I select it, I get the 1 or 0, but I want it to return true/false to my PHP code, without having to rewrite the database.
Can I use another column type? Should I save it differently?
Update: My question is about not wanting to rewrite the returned value. I'm getting a lot of results from my database. Many of those are true/false, but some are 0s because the price is 0, so I don't want to universally rewrite all 1s and 0s. I also don't want to manually rewrite 10 columns.

To follow up my comment, here's a more detailed response which also covers the PHP side, although this probably belongs on StackOverflow.
I've always just used tinyint, although you can use bool/boolean which are synonyms for tinyint(1)
However as of MySQL 5.0.3 you can use the bit type:
As of MySQL 5.0.3, the BIT data type is used to store bit-field values. A type of BIT(M) enables storage of M-bit values. M can range from 1 to 64.
Next, assuming you have an active column, perhaps to store if a user is active, you could use PHP's automatic type conversion to handle this quite simply.
// Obviously you'd replace this with your database call
$results = [['active' => 1], ['active' => 0]];
foreach($results as $row) {
if ($row['active'] == true) {
echo "true\n";
}
else {
echo "false\n";
}
}

You don't strictly need to do anything.
PHP does not, and can not, use strongly typed variables. So, if you receive an (int) 1 from your query results, you can simply use this 1 as a boolean without rewriting or changing anything.
$intOne = (int) 1; //explicitly treat the variable as an integer
var_dump((bool) $intOne); //treat the variable as a boolean
When used in any boolean context, like if ($variable)... then any of these types will be considered to be false by PHP:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
... And, most importantly;
Every other value is considered TRUE (including any resource).
Source: PHP Manual > Booleans (english)
So while you can change the storage type of your column in mysql, this won't really change the way PHP handles the variable retrieved from your results at all.
Historically, I've always used a column of type TINYINT(1) to store boolean values in mysql, and as Tom Green points out, recent mysql versions provide a new BIT type, which might be appropriate. To the best of my knowledge, mysql does not currently have an actual boolean data type.
You could just as easily use a column of type VARCHAR(1), though, because PHP can and will use any value as a boolean, thanks to the glorious, majestic, and sometimes maddening, PHP Type Juggling.
If you're trying to use the values you're retrieving for boolean logic, just use the values you receive from mysql like booleans and it will work:
if ($valueFromResults) {
//The value was something like true
} else {
//The value was something like false
}
If you're trying to actually echo out the words "true" and "false", then you're probably best served by explicitly echoing the words out yourself, like this;
if ($valueFromResults) {
echo "true";
} else {
echo "false";
}
or, in my preferred shorthand;
echo ($valueFromResults) ? "true" : "false" ;
Update You mentioned in a comment that you want to pass the values through json_encode() and use them in javascript.
JavaScript treats any real value, like int 1, as true and any empty value, like int 0, or an empty string, as false. So if your json_encode() output gets used in actual JavaScript, the int values will still work as boolean values. So the integer values from your database should still work as they are.
Just check that your integer results are encoded as integers by PHP and not as strings - they should be encoded correctly by default - because "0" == true in javascript, but 0 == false.

For a boolean value (true/false), you should use the mySql type bit or tinyint(1).
$boolean = $mysql_data ? true : false;

Related

a json.getString() function returns a String of strange format so that It can't be compared to string of seemingly same value

When comparing the output of json.getString() to a string of same value i manually inputted into a json file, it's a false comparison.
println("-");
println(jsonScene.getString("value"));
println(jsonScene.getString("value") == "-");
Outputs
-
-
false
The same value is printed but when compared, it's false but should be true.
Remember in Processing (Java) you need to compare Strings using equals():
Compares two strings to see if they are the same. This method is necessary because it's not possible to compare strings using the equality operator (==). Returns true if the strings are the same and false if they are not.
For example:
println(jsonScene.getString("value").equals("-"));
Check the .charCodeAt(0) for both strings
.trim() both of them before the comparison
Check that typeof jsonScene.getString("value") === "string" (it could be an object with custom toString() defined)

Jlist getSelectValue select both values [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I've been using the == operator in my program to compare all my strings so far.
However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.
Is == bad? When should it and should it not be used? What's the difference?
== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they contain the same data).
Objects.equals() checks for null before calling .equals() so you don't have to (available as of JDK7, also available in Guava).
Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().
// These two have the same value
new String("test").equals("test") // --> true
// ... but they are not the same object
new String("test") == "test" // --> false
// ... neither are these
new String("test") == new String("test") // --> false
// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" // --> true
// ... string literals are concatenated by the compiler
// and the results are interned.
"test" == "te" + "st" // --> true
// ... but you should really just call Objects.equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false
Objects.equals(null, null) // --> true
You almost always want to use Objects.equals(). In the rare situation where you know you're dealing with interned strings, you can use ==.
From JLS 3.10.5. String Literals:
Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.
Similar examples can also be found in JLS 3.10.5-1.
Other Methods To Consider
String.equalsIgnoreCase() value equality that ignores case. Beware, however, that this method can have unexpected results in various locale-related cases, see this question.
String.contentEquals() compares the content of the String with the content of any CharSequence (available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you.
== tests object references, .equals() tests the string values.
Sometimes it looks as if == compares values, because Java does some behind-the-scenes stuff to make sure identical in-line strings are actually the same object.
For example:
String fooString1 = new String("foo");
String fooString2 = new String("foo");
// Evaluates to false
fooString1 == fooString2;
// Evaluates to true
fooString1.equals(fooString2);
// Evaluates to true, because Java uses the same object
"bar" == "bar";
But beware of nulls!
== handles null strings fine, but calling .equals() from a null string will cause an exception:
String nullString1 = null;
String nullString2 = null;
// Evaluates to true
System.out.print(nullString1 == nullString2);
// Throws a NullPointerException
System.out.print(nullString1.equals(nullString2));
So if you know that fooString1 may be null, tell the reader that by writing
System.out.print(fooString1 != null && fooString1.equals("bar"));
The following are shorter, but it’s less obvious that it checks for null:
System.out.print("bar".equals(fooString1)); // "bar" is never null
System.out.print(Objects.equals(fooString1, "bar")); // Java 7 required
== compares Object references.
.equals() compares String values.
Sometimes == gives illusions of comparing String values, as in following cases:
String a="Test";
String b="Test";
if(a==b) ===> true
This is because when you create any String literal, the JVM first searches for that literal in the String pool, and if it finds a match, that same reference will be given to the new String. Because of this, we get:
(a==b) ===> true
String Pool
b -----------------> "test" <-----------------a
However, == fails in the following case:
String a="test";
String b=new String("test");
if (a==b) ===> false
In this case for new String("test") the statement new String will be created on the heap, and that reference will be given to b, so b will be given a reference on the heap, not in String pool.
Now a is pointing to a String in the String pool while b is pointing to a String on the heap. Because of that we get:
if(a==b) ===> false.
String Pool
"test" <-------------------- a
Heap
"test" <-------------------- b
While .equals() always compares a value of String so it gives true in both cases:
String a="Test";
String b="Test";
if(a.equals(b)) ===> true
String a="test";
String b=new String("test");
if(a.equals(b)) ===> true
So using .equals() is always better.
The == operator checks to see if the two strings are exactly the same object.
The .equals() method will check if the two strings have the same value.
Strings in Java are immutable. That means whenever you try to change/modify the string you get a new instance. You cannot change the original string. This has been done so that these string instances can be cached. A typical program contains a lot of string references and caching these instances can decrease the memory footprint and increase the performance of the program.
When using == operator for string comparison you are not comparing the contents of the string, but are actually comparing the memory address. If they are both equal it will return true and false otherwise. Whereas equals in string compares the string contents.
So the question is if all the strings are cached in the system, how come == returns false whereas equals return true? Well, this is possible. If you make a new string like String str = new String("Testing") you end up creating a new string in the cache even if the cache already contains a string having the same content. In short "MyString" == new String("MyString") will always return false.
Java also talks about the function intern() that can be used on a string to make it part of the cache so "MyString" == new String("MyString").intern() will return true.
Note: == operator is much faster than equals just because you are comparing two memory addresses, but you need to be sure that the code isn't creating new String instances in the code. Otherwise you will encounter bugs.
String a = new String("foo");
String b = new String("foo");
System.out.println(a == b); // prints false
System.out.println(a.equals(b)); // prints true
Make sure you understand why. It's because the == comparison only compares references; the equals() method does a character-by-character comparison of the contents.
When you call new for a and b, each one gets a new reference that points to the "foo" in the string table. The references are different, but the content is the same.
Yea, it's bad...
== means that your two string references are exactly the same object. You may have heard that this is the case because Java keeps sort of a literal table (which it does), but that is not always the case. Some strings are loaded in different ways, constructed from other strings, etc., so you must never assume that two identical strings are stored in the same location.
Equals does the real comparison for you.
Yes, == is bad for comparing Strings (any objects really, unless you know they're canonical). == just compares object references. .equals() tests for equality. For Strings, often they'll be the same but as you've discovered, that's not guaranteed always.
Java have a String pool under which Java manages the memory allocation for the String objects. See String Pools in Java
When you check (compare) two objects using the == operator it compares the address equality into the string-pool. If the two String objects have the same address references then it returns true, otherwise false. But if you want to compare the contents of two String objects then you must override the equals method.
equals is actually the method of the Object class, but it is Overridden into the String class and a new definition is given which compares the contents of object.
Example:
stringObjectOne.equals(stringObjectTwo);
But mind it respects the case of String. If you want case insensitive compare then you must go for the equalsIgnoreCase method of the String class.
Let's See:
String one = "HELLO";
String two = "HELLO";
String three = new String("HELLO");
String four = "hello";
one == two; // TRUE
one == three; // FALSE
one == four; // FALSE
one.equals(two); // TRUE
one.equals(three); // TRUE
one.equals(four); // FALSE
one.equalsIgnoreCase(four); // TRUE
I agree with the answer from zacherates.
But what you can do is to call intern() on your non-literal strings.
From zacherates example:
// ... but they are not the same object
new String("test") == "test" ==> false
If you intern the non-literal String equality is true:
new String("test").intern() == "test" ==> true
== compares object references in Java, and that is no exception for String objects.
For comparing the actual contents of objects (including String), one must use the equals method.
If a comparison of two String objects using == turns out to be true, that is because the String objects were interned, and the Java Virtual Machine is having multiple references point to the same instance of String. One should not expect that comparing one String object containing the same contents as another String object using == to evaluate as true.
.equals() compares the data in a class (assuming the function is implemented).
== compares pointer locations (location of the object in memory).
== returns true if both objects (NOT TALKING ABOUT PRIMITIVES) point to the SAME object instance.
.equals() returns true if the two objects contain the same data equals() Versus == in Java
That may help you.
== performs a reference equality check, whether the 2 objects (strings in this case) refer to the same object in the memory.
The equals() method will check whether the contents or the states of 2 objects are the same.
Obviously == is faster, but will (might) give false results in many cases if you just want to tell if 2 Strings hold the same text.
Definitely the use of the equals() method is recommended.
Don't worry about the performance. Some things to encourage using String.equals():
Implementation of String.equals() first checks for reference equality (using ==), and if the 2 strings are the same by reference, no further calculation is performed!
If the 2 string references are not the same, String.equals() will next check the lengths of the strings. This is also a fast operation because the String class stores the length of the string, no need to count the characters or code points. If the lengths differ, no further check is performed, we know they cannot be equal.
Only if we got this far will the contents of the 2 strings be actually compared, and this will be a short-hand comparison: not all the characters will be compared, if we find a mismatching character (at the same position in the 2 strings), no further characters will be checked.
When all is said and done, even if we have a guarantee that the strings are interns, using the equals() method is still not that overhead that one might think, definitely the recommended way. If you want an efficient reference check, then use enums where it is guaranteed by the language specification and implementation that the same enum value will be the same object (by reference).
If you're like me, when I first started using Java, I wanted to use the "==" operator to test whether two String instances were equal, but for better or worse, that's not the correct way to do it in Java.
In this tutorial I'll demonstrate several different ways to correctly compare Java strings, starting with the approach I use most of the time. At the end of this Java String comparison tutorial I'll also discuss why the "==" operator doesn't work when comparing Java strings.
Option 1: Java String comparison with the equals method
Most of the time (maybe 95% of the time) I compare strings with the equals method of the Java String class, like this:
if (string1.equals(string2))
This String equals method looks at the two Java strings, and if they contain the exact same string of characters, they are considered equal.
Taking a look at a quick String comparison example with the equals method, if the following test were run, the two strings would not be considered equal because the characters are not the exactly the same (the case of the characters is different):
String string1 = "foo";
String string2 = "FOO";
if (string1.equals(string2))
{
// this line will not print because the
// java string equals method returns false:
System.out.println("The two strings are the same.")
}
But, when the two strings contain the exact same string of characters, the equals method will return true, as in this example:
String string1 = "foo";
String string2 = "foo";
// test for equality with the java string equals method
if (string1.equals(string2))
{
// this line WILL print
System.out.println("The two strings are the same.")
}
Option 2: String comparison with the equalsIgnoreCase method
In some string comparison tests you'll want to ignore whether the strings are uppercase or lowercase. When you want to test your strings for equality in this case-insensitive manner, use the equalsIgnoreCase method of the String class, like this:
String string1 = "foo";
String string2 = "FOO";
// java string compare while ignoring case
if (string1.equalsIgnoreCase(string2))
{
// this line WILL print
System.out.println("Ignoring case, the two strings are the same.")
}
Option 3: Java String comparison with the compareTo method
There is also a third, less common way to compare Java strings, and that's with the String class compareTo method. If the two strings are exactly the same, the compareTo method will return a value of 0 (zero). Here's a quick example of what this String comparison approach looks like:
String string1 = "foo bar";
String string2 = "foo bar";
// java string compare example
if (string1.compareTo(string2) == 0)
{
// this line WILL print
System.out.println("The two strings are the same.")
}
While I'm writing about this concept of equality in Java, it's important to note that the Java language includes an equals method in the base Java Object class. Whenever you're creating your own objects and you want to provide a means to see if two instances of your object are "equal", you should override (and implement) this equals method in your class (in the same way the Java language provides this equality/comparison behavior in the String equals method).
You may want to have a look at this ==, .equals(), compareTo(), and compare()
Function:
public float simpleSimilarity(String u, String v) {
String[] a = u.split(" ");
String[] b = v.split(" ");
long correct = 0;
int minLen = Math.min(a.length, b.length);
for (int i = 0; i < minLen; i++) {
String aa = a[i];
String bb = b[i];
int minWordLength = Math.min(aa.length(), bb.length());
for (int j = 0; j < minWordLength; j++) {
if (aa.charAt(j) == bb.charAt(j)) {
correct++;
}
}
}
return (float) (((double) correct) / Math.max(u.length(), v.length()));
}
Test:
String a = "This is the first string.";
String b = "this is not 1st string!";
// for exact string comparison, use .equals
boolean exact = a.equals(b);
// For similarity check, there are libraries for this
// Here I'll try a simple example I wrote
float similarity = simple_similarity(a,b);
The == operator check if the two references point to the same object or not. .equals() check for the actual string content (value).
Note that the .equals() method belongs to class Object (super class of all classes). You need to override it as per you class requirement, but for String it is already implemented, and it checks whether two strings have the same value or not.
Case 1
String s1 = "Stack Overflow";
String s2 = "Stack Overflow";
s1 == s2; //true
s1.equals(s2); //true
Reason: String literals created without null are stored in the String pool in the permgen area of heap. So both s1 and s2 point to same object in the pool.
Case 2
String s1 = new String("Stack Overflow");
String s2 = new String("Stack Overflow");
s1 == s2; //false
s1.equals(s2); //true
Reason: If you create a String object using the new keyword a separate space is allocated to it on the heap.
== compares the reference value of objects whereas the equals() method present in the java.lang.String class compares the contents of the String object (to another object).
I think that when you define a String you define an object. So you need to use .equals(). When you use primitive data types you use == but with String (and any object) you must use .equals().
If the equals() method is present in the java.lang.Object class, and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects. Whereas the == operator is expected to check the actual object instances are same or not.
Example
Consider two different reference variables, str1 and str2:
str1 = new String("abc");
str2 = new String("abc");
If you use the equals()
System.out.println((str1.equals(str2))?"TRUE":"FALSE");
You will get the output as TRUE if you use ==.
System.out.println((str1==str2) ? "TRUE" : "FALSE");
Now you will get the FALSE as output, because both str1 and str2 are pointing to two different objects even though both of them share the same string content. It is because of new String() a new object is created every time.
Operator == is always meant for object reference comparison, whereas the String class .equals() method is overridden for content comparison:
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1 == s2); // It prints false (reference comparison)
System.out.println(s1.equals(s2)); // It prints true (content comparison)
All objects are guaranteed to have a .equals() method since Object contains a method, .equals(), that returns a boolean. It is the subclass' job to override this method if a further defining definition is required. Without it (i.e. using ==) only memory addresses are checked between two objects for equality. String overrides this .equals() method and instead of using the memory address it returns the comparison of strings at the character level for equality.
A key note is that strings are stored in one lump pool so once a string is created it is forever stored in a program at the same address. Strings do not change, they are immutable. This is why it is a bad idea to use regular string concatenation if you have a serious of amount of string processing to do. Instead you would use the StringBuilder classes provided. Remember the pointers to this string can change and if you were interested to see if two pointers were the same == would be a fine way to go. Strings themselves do not.
You can also use the compareTo() method to compare two Strings. If the compareTo result is 0, then the two strings are equal, otherwise the strings being compared are not equal.
The == compares the references and does not compare the actual strings. If you did create every string using new String(somestring).intern() then you can use the == operator to compare two strings, otherwise equals() or compareTo methods can only be used.
In Java, when the == operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.
The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory.
This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.
The == operator checks if the two strings are exactly the same object.
The .equals() method check if the two strings have the same value.

Perl if statement, If value = nothing do statement if value = something do statement

I am trying to insert a value from a text box into a SQL table. Although when I leave the text box blank it is adding a blank value which then causes the rest of the form functions to not work.
I want the if statement to check if $animal is blank do nothing. And if $animal has something in it, then to perform the insert into the table.
I am not quite sure what to put where I have put.
if ($animal = " ") {
}
else
if ($animal = "???") {
insertTable("INSERT INTO $table(name) VALUE ('".$animal."')");
Line 24 - 27 is this
sub insertTable {
$statement = shift (#_);
$dbh->do($statement);
} # sub
Perl uses scalar variables, which are quite versatile little things. One of the gotchas with them is that their 'truthiness' isn't always obvious.
If you test a scalar with a Boolean test it will be false if:
It's undefined.
It's an empty string.
It's the number 0.
It's the string "0".
(Arrays test as false if they're undefined or have no elements.)
So the correct answer would be - either used defined to check if the value is defined. Or use a regular expression to pattern match a 'valid' value.
E.g.
if ( $animal =~ m/\w+/ ) {
# Do something
}
\w+ is the Perl regular expression for saying 'one or more word characters' which is alphanumeric and underscore. So your empty string, whitespace only string, or undefined string will all not match this pattern.
Quite a few problems here. Addressing the worst of them:
You're using = which is for assignment, not comparison. Use == to compare numbers and eq to compare strings.
You're comparing your variable to a single space. It's very unlikely that you'll get a single space character in $animal. You'll want to do something either far simpler (if ($animal) { ... }) or more complex (perhaps if ($animal =~ /\w/) { ... }).
You are interpolating user input directly into SQL which you then run against your database. This leads to SQL injection attacks. Far better to use a bind point in your SQL.
In Perl there isn't a null value, only an undefined!
if (defined $value)
{
# Do that
}
else
{
# Do this
}

How does string truthiness work in MySQL?

I wanted to look for records where a certain string field was not blank or null, so I simply wrote SELECT ... FROM myTable WHERE x, assuming that blank and null strings would evaluate to false, but that doesn't appear to be the case.
The string "02306" is true, whereas "N06097EIP" is somehow false.
What's going on?
Edit: I'm aware of the workarounds, I simply want to know how the casting works.
In these expression string are first converted to numbers. "02306" is converted to 2306 which is >0 and therefore considered true, while "N06097EIP" (starting with non-digit) is converted to 0, which is evaluated as false.
Compare results of:
select convert("N06097EIP",signed)
and
select convert("02306",signed)
In a boolean context, such as
WHERE x
the expression x will be evaluated as an integer value. Note that MySQL considers a BOOLEAN as a numeric type.
http://dev.mysql.com/doc/refman/5.1/en/numeric-type-overview.html
It doesn't matter what type the expression x is; it's either an INTEGER type, or it will be converted to an INTEGER type, according to the documented conversion rules.
The end result is that the expression x will be evaluated to be either NULL, integer zero, or integer non-zero.
And those correspond to the boolean "truthiness" values of NULL, FALSE and TRUE.
The reason '02306' is considered TRUE is because this string converts to integer value 2306, which is non-zero.
The reason 'N06097EIP' is considered FALSE is because this string converts to integer value 0.
To can run a simple test case to verify:
SELECT IF( 0 = 'N06097EIP', 'is zero', 'is not zero')
SELECT 0 = 'N06097EIP'
The behavior you observe is entirely expected. It's all pretty straightforward. You may have been caught unawares, because the normative pattern is for us to avoid this type of evaluation and to instead use "workarounds" (as you put it) to return a boolean.
Don't try to be too cute about this with syntactic shortcuts. If nothing else, it's always harder on the next developer who has to figure out what you were doing.
Just spell out what you want.
SELECT *
FROM myTable
WHERE x IS NOT NULL AND x <> '';
or, if you'd prefer:
SELECT *
FROM myTable
WHERE COALESCE(x, '') <> '';

how do I indicate an unset default parameter of type Number in Flex3?

for String and Object type, I can set the default parameter to null to indicate that it was not set by the caller. Is there a mechanism in flex3 to do the same for the Number type?
So for instance:
public function myMethod( stringVar:String=null, ObjectVar:Object=null, numberVar:Number )
{
...
}
I could do the following, but it just feels ugly
public function myMethod( numberVarObj:Object=null )
{
var numberVarSet:Boolean=true;
if( numberVarObj == null ) {
numberVarSet = false;
}
and then everywhere I want to use numberVar I can check for numberVarSet and cast as a Number.
I suppose you could always try:
var numberVar:* = null;
And then set it to a number when you want . . . It would be nice to have a solution that is strongly typed though.
Another option, as specified in Adobe's Docs (scroll down to default values), would be to treat the value NaN as null. However, if your data has ANY chance of containing a NaN value, this is a horrible idea.
I'd recommend the "ugly" solution you have, but if you really want another option you can use NaN and then use isNaN(num) to check the value.