true2self Posted December 18, 2008 Share Posted December 18, 2008 How do I write an if statement within sql. This is what i'm trying to do... select password from usertable where id = 1234 if password = blahblah then flag = 1 else flag = 0. I need to use this flag throughout my php file. Does that make sense? Please help. Link to comment https://forums.phpfreaks.com/topic/137559-mysql-if-statement/ Share on other sites More sharing options...
Maq Posted December 18, 2008 Share Posted December 18, 2008 Read some posts on conditionals in MySQL but also read that it is not supported in general. So, sorry I'm not sure how to do this in MySQL but you can do this in a combination of PHP and MySQL: $sql = "SELECT password FROM usertable WHERE id = 1234"; $result = mysql_query($sql) or die(mysql_error()); $row = mysql_fetch_array($result); $flag = ($row['password'] == "blahblah") ? 1 : 0; $sql_update = "UPDATE usertable SET flag = $flag WHERE id = 1234"; $mysql_query($sql_update) or die(mysql_error()); Link to comment https://forums.phpfreaks.com/topic/137559-mysql-if-statement/#findComment-718952 Share on other sites More sharing options...
true2self Posted December 18, 2008 Author Share Posted December 18, 2008 Thanks Maq! This helps alot! I'm actually trying to apply the flag to an encrypted field, and if it is a certain password then i'm going to flag it, if not then setting it to 0. So my code looks like this just for testing purposes. $pass_check = "SELECT id AS id " . "FROM {$CFG->prefix}user " . "WHERE password= MD5('g4k100') and username = 'aabbott1111'"; $result = mysql_query($pass_check); $some_row = mysql_fetch_array($result); $flag = ($some_row['id'] == 84654) ? 1 : 0; echo $flag; I'm pretty new to PHP, so if my query results are about 100 rows, that should not be a problem correct? I'm changing $flag = ($some_row['id'] == $current_id) ? 1 : 0; and it should still work, correct? Link to comment https://forums.phpfreaks.com/topic/137559-mysql-if-statement/#findComment-718963 Share on other sites More sharing options...
Maq Posted December 18, 2008 Share Posted December 18, 2008 $pass_check = "SELECT id AS id " . I don't think you need id AS id, just SELECT id . and it should still work, correct? Yes, it should. I'm not sure how you get $current_id, session maybe? Anyway, it's called a ternary operator. Basically it translates to: if($some_row['id'] == $current_id) { $flag = 1; } else { $flag = 0; } Let me know how it all turns out. Link to comment https://forums.phpfreaks.com/topic/137559-mysql-if-statement/#findComment-718995 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.