Jump to content

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


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
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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