Return a value from else section of if statement

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sheepysheep
Forum Newbie
Posts: 9
Joined: Mon Oct 12, 2009 8:14 am

Return a value from else section of if statement

Post by sheepysheep »

Hello, I'm quite new to php and am trying to make a site where you can upload files. As I don't want to over write files I've made some (probably horribly written) code to check its name and add a bracketed number on the end. It is two functions, one to check the name against a database and the other to change it (if necessary). I want to put the files url (or url-to-be) as the argument, and return the new, non-duplicating url.

If you look at the end of my code, it returns this value. The only problem is, it will only return the value if it is NOT a duplicate file - i.e. if it launches into the other function (checkBrackets) it forgets all about the fact it was going to return a function to my other lines of code.

Code: Select all

 
<?php
//$WORD IS THE CURRENT FILE NAME
function checkBrackets($word)
{
    //STRIP OFF (AND SAVE) THE EXTENSION
    $ext = strrchr($word, ".");
    $ext_length = strlen($ext);
    $extless = substr($word, 0, -$ext_length);
    
    //IF THE NEW FILE ENDS IN '(*)'
    if(substr("$extless", -3, 1) === "(" && substr("$extless", -1, 1) === ")")
    {
        $version_number = substr("$extless", -2, 1);
        //IF THE BIT BETWEEN THE NUMBER IS NUMRERIC, INCREMENT BY 1
        if(is_numeric($version_number))
        {
            ++$version_number;
            $extless = substr_replace($extless,"$version_number" . ")",-2);
            echo "the new name is: " . $extless . "<br/>";
            $new_name = $extless . $ext;
            //CHECK THIS NEW NAME IN THE DATABASE
            checkDatabaseEntry($new_name,1);
        }
        else
        {
            // ELSE PUT SOME BRACKETS ON WITH A NUMBER
            $extless .= "(1)";
            $new_name = $extless . $ext;
            checkDatabaseEntry($new_name,1);
            //CHECK THIS NEW NAME IN THE DATABASE
        }
    }
    else
    {
        //OR IF THERE WERE NO BRACKETS ON IT IN THE FIRST PLACE, ADD THEM
        $extless .= "(1)";
        //REBUILD THE FULL NAME WITH EXTENSION
        $new_name = $extless . $ext;
        checkDatabaseEntry($new_name,1);
    }
} 
 
function checkDatabaseEntry($url,$folder)
{
    echo " / / CHECK FILE NAME: / / <br/>";
    $conn_server = "----";
    $conn_user = "----";
    $conn_pword = "----";
    $con = mysql_connect($conn_server, $conn_user, $conn_pword);
    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }
    else
    {
        //
    }
    mysql_select_db("----");
    
    $duplicate = false;
    $query = "SELECT * FROM files WHERE folder_id=$folder";
    $results = mysql_query($query);
    
    if(!$results = mysql_query("SELECT * FROM files WHERE folder_id=$folder"))
    {
        die(mysql_error());
    }
    
    while($line = mysql_fetch_array($results)) 
    {
        //IF THE FILE'S URL-TO-BE IS ALREADY TAKEN, MARK IT AS DUPLICATE
         if($url === $line["url"]){
             $duplicate = true;
             mysql_close($con);
             break;
         }
         else
         {
            echo "not this one...<br/>";
         }
    }
    
    if($duplicate === true)
    {
        echo "the file name was a duplicate<br/>";
        checkBrackets($url);
    }
    
    else
    {
        //----THIS IS THE BIT THAT ISN'T WORKING AS I'D LIKE
        return $url;
        //----------------------
    }
}
?>
oh yes and the way I am calling this (incase i'm doing it wrong) is:

Code: Select all

 
<?php
    $folder = 1;
    echo checkDatabaseEntry("http://localhost/stuf/files/Presentation_1/1(1).jpg",$folder);
?>
 
It does work very nicely, really, its just hard to make it return something nicely!! Any help is really really appreciated, I'm very new to this and have been struggling a bit!! Many thanks in advance,

Dave
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: Return a value from else section of if statement

Post by Eric! »

sheepysheep wrote:The only problem is, it will only return the value if it is NOT a duplicate file - i.e. if it launches into the other function (checkBrackets) it forgets all about the fact it was going to return a function to my other lines of code.
What do you mean it forgets to "return a function"? It is either going to execute lines 86 and 87 OR line 93. It won't do both because the ELSE statement keeps those sets of code isolated based on the IF condition. If I understand you correctly you probably want the end of your code to look like this:

Code: Select all

   if($duplicate === true)
    {
        echo "the file name was a duplicate<br/>";
        checkBrackets($url);
    }
    return $url;
}
?>
This way your code will return something whether it is duplicated or not.
User avatar
Weiry
Forum Contributor
Posts: 323
Joined: Wed Sep 09, 2009 5:55 am
Location: Australia

Re: Return a value from else section of if statement

Post by Weiry »

sheepysheep wrote:The only problem is, it will only return the value if it is NOT a duplicate file
sheepysheep wrote:and return the new, non-duplicating url.
Im not sure where you are going with this... I thought you mentioned that you wanted a non duplicated url?
Based on the code you have, it will only ever return a non-duplicated code because it will continue looping.


I have notice a couple of other things though.

Code: Select all

   $query = "SELECT * FROM files WHERE folder_id=$folder";
    $results = mysql_query($query);
   
    if(!$results = mysql_query("SELECT * FROM files WHERE folder_id=$folder"))
    {
        die(mysql_error());
    }
You dont need to redeclare the query inside the IF statement, it can simply be written as

Code: Select all

$query = "SELECT * FROM `files` WHERE `folder_id` = '{$folder}'";
    $results = mysql_query($query);
    if(!$results){
        die(mysql_error());
    }
you may have noticed also, i wrapped the variable and made it a string variable so anything received will only be interpreted as a string, this is important to do to help prevent from SQL Injection.

The other thing im curious about is, why are you using a type comparison on a boolean variable in your final IF statement?
You should only need to have:

Code: Select all

if($duplicate){
        echo "the file name was a duplicate<br/>";
        checkBrackets($url);
    }
    return $url;
   
sheepysheep
Forum Newbie
Posts: 9
Joined: Mon Oct 12, 2009 8:14 am

Re: Return a value from else section of if statement

Post by sheepysheep »

Thank you both for your quick replies,

@eric!
I want to use the result of the checkDatabaseEntry, if I let that happen then my upload will over write another file's url if it already exists - that's why I only wanted it to return the value on the 'else' side.

@Weiry
Sorry, I don't think I explained it quite right, if the argument is not a duplicate file to begin with - the first argument I send in - then it will return the value. If it is a duplicate file then it will execute my bit of code (checkBrackets) to add a unique number on the end but then it won't return a value... which I am now noticing is probably because of the way I'm calling it again from a different function. Thank you so much for your other tips though - don't be curious about why i did certain things the only reason I have done those things is because I'm a complete novice!! :?

If you have any advice on how I might get it to return the unique value I'd be really appreciative - but at the same time I'm really up for just sorting it out myself. I feel if I can get both functions sort of tied into 1 I'll be closer...

Many thanks, both of you
User avatar
Weiry
Forum Contributor
Posts: 323
Joined: Wed Sep 09, 2009 5:55 am
Location: Australia

Re: Return a value from else section of if statement

Post by Weiry »

Well for the moment, all i think i manage to do was improve the code quallity (sorry),
as it is about 2:10am my mind isnt working 100%.
But, if this doesnt solve your problem, then i would say its definitely a problem how and where your code are calling the external function.

Code: Select all

function checkDatabaseEntry($url,$folder)
{
    echo " / / CHECK FILE NAME: / / <br/>";
    $conn_server = "----";
    $conn_user = "----";
    $conn_pword = "----";
    $con = mysql_connect($conn_server, $conn_user, $conn_pword) or die('Could not connect: ' . mysql_error());
    mysql_select_db("----");
 
    $query = "SELECT * FROM `files` WHERE `folder_id` = '{$folder}'";
    $results = mysql_query($query);
        if(!$results){ die(mysql_error());}
   
    //IF THE FILE'S URL-TO-BE IS ALREADY TAKEN, MARK IT AS DUPLICATE
    while($line = mysql_fetch_array($results)){
        if($url == "{$line['url']}"){
            mysql_close($con);
            echo "the file name was a duplicate<br/>";
            checkBrackets($url);
            return NULL;
        }
    }
    return $url;
}
But just run that and see if that makes a difference. because this way the code will never reach the final return unless the $url is unique from all others. If it still doesnt work, then it has something to do with the $url getting passed between each function of how the checkBrackets() function is calling checkDatabase().

When i debug my own code, i put lots of print's throughout the code, before and after variables are being changed. This way i can see exactly what is going on. I would suggest doing something similar, just printing out your $url's etc throughout the functions and see what your functions are/aren't doing. That may give you a clearer picture.
Post Reply