4 Replies - 713 Views - Last Post: 22 November 2012 - 09:16 AM Rate Topic: -----

#1 laytonsdad  Icon User is offline

  • Cheese and Sprinkles
  • member icon

Reputation: 436
  • View blog
  • Posts: 1,841
  • Joined: 30-April 10

Advise on existing nested if else statments

Posted 14 November 2012 - 10:03 PM

I am working on a site that I have been building for some time and i came across somthing I had written in the past and wondered if there might be a simpler or faster executing method to use.

Code:
        //check for directories
        if (is_dir("music")){
            if (is_dir("music/users")){
                if (is_dir($fileUrl)){
                    if(move_uploaded_file($fileTempLocation, "music/users/".$_SESSION['logged_in_user']."/".$fileName)){
                        //add to database
                        if (isset($mysqli)){
                            //connection is made to mysql server $mysqli as an object
                            if($preStmtIn = $mysqli->prepare("INSERT INTO artist_songs(id, uid, band, song, album, size, url, imgUrl) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")){
                                $preStmtIn->bind_param("ssssssss", $fileId, $_SESSION['uid'], $_SESSION['abName'], $fileName, $albumName, $fileSize, $fileUrl, $imgUrl);
                                $inserted = $preStmtIn->execute();
                                
                                //insert to artist_songs completed
                                if($inserted){
                                    if($preStmt = $mysqli->prepare("SELECT id, uid, song, album, size, url, imgUrl FROM artist_songs WHERE uid=?")){
                                        $preStmt->bind_param("s", $_SESSION['uid']);
                                        $preStmt->execute();
                                        $preStmt->bind_result($id,$uid,$song,$album,$size,$url,$imgUrl);
                                        
                                        while($preStmt->fetch()){
                                            printf("<b>id:</b> %s <b>uid:</b> %s <b>Song:</b> %s <b>Album:</b> %s <b>Size:</b> %s <b>url:</b> %s <b>Album cover:</b> %s<br/>", $id, $uid, $song, $album, $size, $url, $imgUrl);
                                        }
                                    }
                                }else{
                                    echo "Error:" . mysqli_error($mysqli);
                                }
                            }else{
                                echo "Could not prepare statment!";
                            }
                        }else {
                            echo "mysqli is not connected: " . mysqli_error($mysqli);
                        }
                    }else{
                        print "Error: file was not able to be moved;";
                    }
                }else{
                    mkdir("music/users/".$_SESSION['logged_in_user']);
                }
            }else{
                mkdir("music/users");
            }
        }else{
            mkdir("music");
        }


This checks for directories then moves the uploaded file to the users allocated files folder. It then will check for MySQLi connection and try to insert information to the database. Then it simply echos out the users data.
It works OK yet slow. I am not sure if its the code here but this is what caught my eye as I was looking through the code tonight.
Any wisdom would be appreciated.

Is This A Good Question/Topic? 0
  • +

Replies To: Advise on existing nested if else statments

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3515
  • View blog
  • Posts: 10,142
  • Joined: 08-June 10

Re: Advise on existing nested if else statments

Posted 15 November 2012 - 01:04 AM

Id cut that at least in 2 parts (functions). one where you test and create directories and another where you do the database stuff.

after that you can revert the if/else nesting.
try
{
    if (!$condition1) {
        throw new Exception("error1");
    }
    if (!$condition2) {
        throw new Exception("error2");
    }
    // do stuff
}
catch (Exception $e)
{
    echo $e->getMessage();
}



similarly you can handle the MySQLi errors through Exceptions (and thats why I prefer PDO where Exception handling is built-in).

if uid in the DB is UNIQUE or PRIMARY KEY, there is no need of a while() loop for fetching.

maybe vprintf() may a bit easier here than printf().

you may also consider using MySQLi_Stmt::getResult() since handling MySQLi prepared statement objects is a pain in the a*** (another reason I use PDO).
Was This Post Helpful? 1
  • +
  • -

#3 laytonsdad  Icon User is offline

  • Cheese and Sprinkles
  • member icon

Reputation: 436
  • View blog
  • Posts: 1,841
  • Joined: 30-April 10

Re: Advise on existing nested if else statments

Posted 20 November 2012 - 10:35 PM

So I began to make some functions to do the file directory checking and I seem to be misunderstanding how mkdir() works because I get:

Quote

Warning: mkdir() [function.mkdir]: File exists in /home/jingllec/public_html/core/library/functionLibrary.php on line 9

When the directory already exists instead of it moving on to the next part of the function, the returns.
This is the code that I am using now and I have also tried to use it so that I am checking for the directory not to be there and I get the same result.
<?php
//check if users directory exists
//@param $bandName is $_SESSION["abName"]
function checkUserDirExists($bandName){
    if(is_dir('music/users/'. $bandName)){
        return true;
        exit();
    }else{
        if(mkdir($_SERVER['DOCUMENT_ROOT'] . "/music/users/" . $bandName)){
            return true;
        }else{
            return false;
        }
    }
}


//test call
checkUserDirExists("testBand");
?>


The manual states that this should return a Boolean, but all I get is this warning. Can someone please enlighten me as to why this is giving me a warning instead of exiting the if statement and giving me a return as I expect.

Also, I have no issues if the directory does not exist.
Was This Post Helpful? 0
  • +
  • -

#4 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3515
  • View blog
  • Posts: 10,142
  • Joined: 08-June 10

Re: Advise on existing nested if else statments

Posted 20 November 2012 - 11:47 PM

I could imagine that the given name already exists, but is not a directory (the other condition is_dir() returns false).
Was This Post Helpful? 0
  • +
  • -

#5 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2911
  • View blog
  • Posts: 10,085
  • Joined: 08-August 08

Re: Advise on existing nested if else statments

Posted 22 November 2012 - 09:16 AM

Line 5 uses a relative address but line 9 may be using an absolute address because $_SERVER['DOCUMENT_ROOT'] might be null.

http://php.net/manua...d.variables.php
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1