Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I wrote a function in php which updates a mysql-table according to a given array. Before updating, I check whether there already exists an entry with the same ‚description‘-value.

// $fachtyp is given by foreach
$query = "SELECT IF(EXISTS(SELECT 1 FROM fachtyp WHERE `Description`='$fachtyp'),'true','false')"
    . " AS existance";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($result);
$exists = ($row['existance'] === 'true');
if (!$exists) { /* update */ }

The problemis as follows: When I debugged this, i recognised $row['exists'] to be twhile debugging) to return 'false' in netbeans. How can this happen??

Thx fer reply, Lukas

share|improve this question
2  
Please, before you write any more SQL interfacing code, you must read up on proper SQL escaping to avoid severe SQL injection bugs. When using mysqli you should be using parameterized queries and bind_param to add user data to your query. Never use string interpolation to accomplish this. – tadman Sep 12 '13 at 18:43
1  
You're comparing it to 'true' as a string. Try replacing it with == true (with out quotes)? – Ofir Baruch Sep 12 '13 at 18:43
    
@OfirBaruch That seems like the answer, so you should post it as such. – tadman Sep 12 '13 at 18:44
    
just wondering why you choose to use such SQL query when PHP can perfectly fine use inner SELECT 1 ... and act accordingly? – Ivan Hušnjak Sep 12 '13 at 18:45
1  
did you tried to use var_dump($row); to see what actually is returned as result? – Ivan Hušnjak Sep 12 '13 at 18:49
up vote 0 down vote accepted

First check what is actually the query and returned result:

echo $query; // debug query
var_dump($row); // see what is returned

I would suggest you replace the sql query (unless you really have to have it executed like that) with simpler query, and work out the logic (true, false) with php:

$query = "SELECT 1 FROM fachtyp WHERE `Description`='$fachtyp'";
$result = mysqli_query($con, $query);
$exists = (bool) mysqli_num_rows($result); // just count returned rows is enough to determine if value exists in database
if (!$exists) { /* update */ }

Also if $fachtyp value is coming from request (GET or POST value, actually even if it does not come from request), you should use mysqli_real_escape_string() to sanitize value before putting it into query.

share|improve this answer
    
Yep, dats workin. But anyway I wonder why the values wer that different… I tracked everything with xdebug on netbeans… – Luke Sep 12 '13 at 19:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.