Jump to content

[SOLVED] Why is the logic of this simple code not working?


keldorn

Recommended Posts

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? :smoker:

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....

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? :pirate:

 

//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}'") ;

}

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
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.