0

i am updating name , email in DB of registered user through php form. its working fine.

form

<form action="profile.php" method="POST" enctype="multipart/form-data">

Name : 
<input type="text" name="txtuname" value="<?php echo $row['userName'] ?>" /><br/>
Email :
<input type="text" name="txtemail" value="<?php echo $row['userEmail'] ?>" /><br>
Image
<input type="file" name="photo" id="fileSelect"><br> 

<input type="submit" name="submit" value="Save" />

</form>

form related code to save in db [profile.php ]

$user_home = new USER();

if(!$user_home->is_logged_in())
{
    header("Location: index.php");
die();
}

if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path

$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);

if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid))
{
    header("Location: profile1.php");
   die(); 
}
}

$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);

after this, now i am uploading an image to folder through same php form successfully with below code.

if(isset($_FILES["photo"]["error"])){ 
if($_FILES["photo"]["error"] > 0){ 
echo "Error: " . $_FILES["photo"]["error"] . "<br>"; 

} else{ 
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png"); 
$filename = $_FILES["photo"]["name"]; 
$filetype = $_FILES["photo"]["type"]; 
$filesize = $_FILES["photo"]["size"]; 

// Verify file extension 
$ext = pathinfo($filename, PATHINFO_EXTENSION); 
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format."); 

// Verify file size - 5MB maximum 
$maxsize = 5 * 1024 * 1024; 
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit."); 

// Verify MYME type of the file 
if(in_array($filetype, $allowed)){ 
// Check whether file exists before uploading it 
if(file_exists("upload/" . $_FILES["photo"]["name"])){ 
echo $_FILES["photo"]["name"] . " is already exists."; 

} else{ 
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]); 

echo "Your file was uploaded successfully."; 
} 
} else{ 

echo "Error: There was a problem uploading your file - please try again."; 
} 

} 

} else{ 
echo ""; 
} 

now images are just saving in folders, what i need is i want that image path to save in database and assign that image path to uploaded user in database.

i tried below code , but not working:

class.user.php

<?php
    $dbConn = new Database();
    $dbConn->dbConnection();

    $user_home = new USER();

    function uploadUserPhoto($uid) {
        global $dbConn;
        if(isset($_FILES["photo"]["error"])) {
            if($_FILES["photo"]["error"] > 0) {
                echo "Error: " . $_FILES["photo"]["error"] . "<br>";

            } else {
                $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
                $filename = $_FILES["photo"]["name"];
                $filetype = $_FILES["photo"]["type"];
                $filesize = $_FILES["photo"]["size"];

                $userDir = $uid;

                // Verify file extension
                $ext = pathinfo($filename, PATHINFO_EXTENSION);
                if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");

                // Verify file size - 5MB maximum
                $maxsize = 5 * 1024 * 1024;
                if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");

                // Verify MYME type of the file
                if(in_array($filetype, $allowed)) {
                    if(!is_dir('upload/'.$uid)) {
                        mkdir('upload/'.$uid);
                    }

                    $photoname = time().$uid.'_photo'.'.'.$ext;

                    // delete all the files in this directory
                    $files = glob('upload/'.$uid.'/*'); // get all file names
                    foreach($files as $file){ // iterate files
                        if(is_file($file))
                            unlink($file); // delete file
                    }

                    // Upload the photo
                    move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $uid . '/'. $photoname);

                    $updateData = array(':userID' => $uid, ':photo' => $photoname);
                    $stmt = $dbConn->conn->prepare("UPDATE tbl_users SET photo=:photo WHERE userID=:uid");
                    $stmt->execute($updateData);

                    echo "Your file was uploaded successfully.";
                } else {
                    echo "Error: There was a problem uploading your file - please try again.";
                }
            }
        } else {
            echo "";
        }
    }

profile.php

if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid))
    {
        uploadUserPhoto($uid);
        header("Location: profile1.php");
        die();
    }

i am struggling from last 2 days, please help me . complete code : class.user.php : http://pastebin.com/vh8FvHP2 , profile.php : http://pastebin.com/s0zJuJik , db connection : http://pastebin.com/rYLWBAHi

i will provide 50 bounty points if it worked for me once i gain 50 points....

  • _"not working"_ is a extremely vague and very unhelpful error message, please update your question to describe: What isn't working? What error messages are you getting? – Epodax Oct 26 '16 at 07:06
  • i dont know why downvotes, if you tell reason, i will learn from you...... –  Oct 26 '16 at 07:07
  • @Epodax Thanks for suggestion, i am not getting any error message –  Oct 26 '16 at 07:08
  • Have you turned on error reporting? But even if you're not getting any error messages you will have to explain what isn't working, We're not gonna walk through your code and try and guess what's wrong. – Epodax Oct 26 '16 at 07:10
  • @Epodax i updated question title, images are saving in folder, but i want to save those folder paths in database, when i tried code, those image paths are not saving in database.... –  Oct 26 '16 at 07:13
  • Do you get nothing stored in the database `photo` column or the wrong thing stored – RiggsFolly Oct 26 '16 at 08:07
  • @RiggsFolly nothing is storing in `photo`column..... –  Oct 26 '16 at 09:05
  • @RiggsFolly i followed this : http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php but no errors are displaying.... seems i am doing wrong somewhere.... –  Oct 26 '16 at 09:13

1 Answers1

0

Inside the File: class.user.php; why don't you save the Photo to the Database only after you have successfully moved the uploaded file? The Snippet here attempts to see it from that Perspective:

<?php   

    // Verify MIME type of the file
    if(in_array($filetype, $allowed)) {
        if(!is_dir('upload/'.$uid)) {
            mkdir('upload/'.$uid);
        }

        $photoname = time().$uid.'_photo'.'.'.$ext;

        // delete all the files in this directory
        $files = glob('upload/'.$uid.'/*'); // get all file names
        foreach($files as $file){ // iterate files
            if(is_file($file))
                unlink($file); // delete file
        }
        // SAVE THE  PHOTO TO DATABASE
        // ONLY IF THE PHOTO HAS BE SAVED ON THE FILE-SYSTEM
        if(move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $uid . '/'. $photoname)){

            // NOTICE THERE'S NO COLONS (:) HERE - JUST KEY-VAL PAIRS       
            $updateData = array('uid' => $uid, 'pix' => "upload/" . $uid . "/" . $photoname);
            $stmt = $dbConn->conn->prepare("UPDATE tbl_users SET photo=:pix WHERE userID=:uid");
            $stmt->execute($updateData);                
            echo "Your file was uploaded successfully.";                
        }

    } else {
        echo "Error: There was a problem uploading your file - please try again.";
    }
Poiz
  • 7,611
  • 2
  • 15
  • 17
  • i replaced your code in function `uploadUserPhoto` , but still image is not saving, please check full code here : http://pastebin.com/U9wkytmr –  Oct 26 '16 at 09:11
  • @abcd do Photos get uploaded? – Poiz Oct 26 '16 at 09:20
  • @abcd within the `if(move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $uid . '/'. $photoname)){` Try to var_dump() the result of the database query like: `var_dump( $stmt->execute($updateData))` What did you get? – Poiz Oct 26 '16 at 09:23
  • one registered user is can upload unlimited number of photos, but i wanted to avoid that , so if we save image path in database column, than again if that user upload image, it should replace old image, but that is not happening now.... –  Oct 26 '16 at 09:24
  • i added this code : `var_dump( $stmt->execute($updateData));` after line `echo "Your file was uploaded successfully."; ` , but still it did't display any error messages..... –  Oct 26 '16 at 09:27
  • @abcd Check that the Query `"UPDATE tbl_users SET photo=:pix WHERE userID=:uid"` is Correct. – Poiz Oct 26 '16 at 09:30
  • i ran this query : `UPDATE tbl_users SET photo=:pix WHERE userID=:uid;` , i got error : `#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':pix WHERE userID=:uid' at line 1` –  Oct 26 '16 at 09:33
  • @abcd sure! you'd get an error if you run it like that... you have to replace `:uid` and `:pix` with some real value..... – Poiz Oct 26 '16 at 09:36
  • i am sorry, i didt know that, i got `uid` value : 22, please tell how to find : `:pix` value ? –  Oct 26 '16 at 09:37
  • @abcd try `var_dump( "upload/" . $uid . "/" . $photoname);` inside the `IF` block. That is the pix value – Poiz Oct 26 '16 at 09:40
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/126706/discussion-between-abcd-and-poiz). –  Oct 26 '16 at 09:44