keldorn Posted October 29, 2009 Share Posted October 29, 2009 Hey, I'm trying to determine if a table already exists in mysql, but doing a query first with mysql_query, then checking $sql as if it a were TRUE of FALSE. Which I though it would be. My Code always skips to the }else{ statment after the If(). What is wrong, How I do this? I could of sworn I've wrote other scripts using this and it works. PHP: //Check first if it exists $sql = mysql_query("SELECT var FROM fake WHERE token='{$token}'"); if( ! $sql){ // Does not exist! Create it. $sql = mysql_query("INSERT INTO fake (var,token) VALUES('$var','$token')") ; } else { //It exists, Update it. $sql = mysql_query("UPDATE fake SET var='{$var}' WHERE token='{$token}'") ; } Also echo $sql; prints out, Resource id #11 or something.. Doesn't seem to say false or true.... Link to comment https://forums.phpfreaks.com/topic/179451-solved-why-is-the-logic-of-this-simple-code-not-working/ Share on other sites More sharing options...
keldorn Posted October 29, 2009 Author Share Posted October 29, 2009 This works, mysql_fetch_row() returns FALSE, according the documentation, if the there is no Array created. So I can assume that the false means the table does not exist and can proceed with if(!$sql){} Also with error_reporting(E_ALL); it generates no PHP error messages in the top of page. So putting a @ in not necessary in front the mysql_fetch_row(). Good way to check if a row exists in mysql table? //Check first if it exists $sql = mysql_query("SELECT var FROM fake WHERE token='{$token}'"); $sql = mysql_fetch_row($sql); if(!$sql){ // Does not exist! Create it. $sql = mysql_query("INSERT INTO fake (var,token) VALUES('$var','$token')") ; } else { //It exists, Update it. $sql = mysql_query("UPDATE fake SET var='{$var}' WHERE token='{$token}'") ; } Link to comment https://forums.phpfreaks.com/topic/179451-solved-why-is-the-logic-of-this-simple-code-not-working/#findComment-946830 Share on other sites More sharing options...
ngreenwood6 Posted October 29, 2009 Share Posted October 29, 2009 Well first of all you are not trying to see if a table exists, you are trying to see if a row exists. There are multiple ways to do this and here is probably the most common way: //perform the query $sql = mysql_query("SELECT var FROM fake WHERE token='{$token}'"); //get the number of rows $num_rows = mysql_num_rows($sql); if($num_rows > 0){ //put update query here } else { //put insert query here } Link to comment https://forums.phpfreaks.com/topic/179451-solved-why-is-the-logic-of-this-simple-code-not-working/#findComment-946832 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.