-3

I have this code, everything works except on adding image, image is uploaded thru form and supposed to save/update it on the database.

the problem is it doesnt upload the file on my table . (user_image). images are save on the uploads/profile/image/ directory with no problem.

can you please help me what is wrong in ths code. thank you.

<?php
include_once 'config.php';
if(isset($_POST['btn-upload']))
{    

$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];

$folder="uploads/profile/image/";



// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case

$final_file=str_replace(' ','-',$new_file_name);

if(move_uploaded_file($file_loc,$folder.$final_file))
{

    $sql="update user SET user_image='$file' where username = '$username'";
    mysql_query($sql);
    ?>
    <script>
    alert('image successfully uploaded');
    window.location.href='profile.php?success';
    </script>
    <?php
}
else
{
    ?>
    <script>
    alert('error while uploading file');
    window.location.href='profile.php?fail';
    </script>
    <?php
    }
    }
    ?>

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit" name="btn-upload">upload</button>
</form>
Randy Corpuz
  • 153
  • 1
  • 10
  • 4
    Please, [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://jayblanchard.net/demystifying_php_pdo.html). Add error reporting to the top of your file(s) right after your opening ` – Jay Blanchard Apr 21 '15 at 17:41
  • What type of field is `user_image` of? it should be `TEXT` and keep the path to the file, don't upload images directly on to the table. – odedta Apr 21 '15 at 17:45
  • what do you mean type of field? sorry im lost – Randy Corpuz Apr 21 '15 at 17:46
  • @odedta It is just saving the path, and a `VARCHAR(1024)` field should be sufficient. There's no need to use `TEXT` here. – tadman Apr 21 '15 at 17:47
  • True, you need to debug both your mysql _queries and your upload query, always put a query inside an `if` statement so if it doesn't work you can use `mysql_error()` or in the improved version `mysqli->errno` – odedta Apr 21 '15 at 17:50
  • you sure you want to do an `update` rather than an `INSERT`? Add error reporting to the top of your file(s) right after your opening PHP tag for example ` – Funk Forty Niner Apr 21 '15 at 18:01
  • I think insert will create new set of rows.. And I have a existing row and I only need to update the user_image field. – Randy Corpuz Apr 21 '15 at 18:07
  • instead of `SET user_image='$file'` you probably want `SET user_image='$final_file'` plus you're probably trying to insert something in there that MySQL isn't agreeing with. `or die(mysql_error())` to `mysql_query()` will tell you that. – Funk Forty Niner Apr 21 '15 at 18:07
  • @fred tried that already. – Randy Corpuz Apr 21 '15 at 18:09
  • what about error reporting; did you add that to your page(s)? do a `var_dump();` and see what's going through or not. – Funk Forty Niner Apr 21 '15 at 18:10
  • ***woah... hold on there cowboy;*** here's the problem and it just dawned on me; your `where username = '$username'` where is that username defined? it isn't in your code and that is why it's not working. Error reporting should have informed you of an undefined variable. – Funk Forty Niner Apr 21 '15 at 18:12
  • ok where are we at here? I was going to post an answer in regards to my last comment because I'm sure that's what the problem is; but I haven't heard from you since. – Funk Forty Niner Apr 21 '15 at 18:22
  • ok closing this tab. good luck. – Funk Forty Niner Apr 21 '15 at 18:27
  • @Fred-ii- adding $username = $_SESSION['username']; solve the problem. thanks for the tip. – Randy Corpuz Apr 22 '15 at 07:46
  • You're welcome Randy. – Funk Forty Niner Apr 22 '15 at 12:54

1 Answers1

1

Here is a function that includes a few checks, some of whic are allowed extensions and checks if the destination directory exists I wrote:

$allowedExts = array("doc","docx","pdf","jpeg","jpg","png");
$path_parts = pathinfo($_FILES[$filename]["name"]);
$extension = strtolower($path_parts["extension"]); 
if ((($_FILES[$filename]["type"] == "application/msword")
|| ($_FILES[$filename]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
|| ($_FILES[$filename]["type"] == "application/pdf")
|| ($_FILES[$filename]["type"] == "image/jpeg")
|| ($_FILES[$filename]["type"] == "image/jpg")
|| ($_FILES[$filename]["type"] == "image/png"))
&& ($_FILES[$filename]["size"] < 3*1024000)
&& in_array($extension, $allowedExts)
&& ($_FILES[$filename]['error'] === UPLOAD_ERR_OK)) {
    $destination = 'uploads/'.$_SESSION['user_id'];
    if(!file_exists($destination)) {
        mkdir($destination);
    }
    move_uploaded_file($_FILES[$filename]['tmp_name'],$destination.'/'.$_FILES[$filename]['name']);
    if(strcmp($filename,'file_1') == 0)
        $query = "UPDATE step_3 SET files_user_id=? WHERE user_id=?";
    if(strcmp($filename,'file_2') == 0)
        $query = "UPDATE step_3 SET files_cv=? WHERE user_id=?";
    if(strcmp($filename,'file_3') == 0)
        $query = "UPDATE step_3 SET files_diploma=? WHERE user_id=?";
    if(strcmp($filename,'file_4') == 0)
        $query = "UPDATE step_3 SET files_grades=? WHERE user_id=?";
    if(strcmp($filename,'file_5') == 0)
        $query = "UPDATE step_3 SET files_profile_pic=? WHERE user_id=?";
    if($stmt = $mysqli->prepare($query)) {
        $stmt->bind_param('ss',$_FILES[$filename]['name'],$_SESSION['user_id']);
        $stmt->execute();
        $stmt->close();
        redirect_to('filename.php','0');
    }
    else {
        show_feedback_alert('error, try again', 'danger', 'exclamation-sign');
    }
    return true;
}
else {
    switch($_FILES[$filename]['error']) {
        case UPLOAD_ERR_INI_SIZE: 
            $message = "too big"; 
            break; 
        case UPLOAD_ERR_FORM_SIZE: 
            $message = "too big";
            break;
        case UPLOAD_ERR_PARTIAL: 
            $message = "partially uploaded"; 
            break; 
        case UPLOAD_ERR_NO_FILE: 
            $message = "error 1"; 
            break; 
        case UPLOAD_ERR_NO_TMP_DIR: 
            $message = "error 2"; 
            break; 
        case UPLOAD_ERR_CANT_WRITE: 
            $message = "error 3"; 
            break; 
        case UPLOAD_ERR_EXTENSION: 
            $message = "error 4"; 
            break;
        default: 
            $message = "error 5"; 
            break; 
    }
    show_feedback_alert($message, 'danger', 'exclamation-sign');
    return false;
}

you need to debug both your mysql queries and your upload query, always put a query inside an if statement so if it doesn't work you can use mysql_error() or in the improved version mysqli->errno

odedta
  • 2,430
  • 4
  • 24
  • 51