简体   繁体   中英

php sql upload picture to logged in user

Hello I want to upload a pic to phpmyadmin and to store it to the loggen in user but can't manage it. And when I succed on uploading the image it goes to the first user.Want to return some rows of the table, but of the logged in user! Here is the code! Thanks

include('functions.php');
$upload_dir = 'images/';


if(isset($_FILES['image'])){
    $errors= array();
    $file_name = $_FILES['image']['name'];
    $file_size =$_FILES['image']['size'];
    $file_tmp =$_FILES['image']['tmp_name'];
    $file_type=$_FILES['image']['type'];
    $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));


    echo $file_name;
    echo '<br>';
    echo $file_size;
    echo '<br>';
    echo $file_tmp;
    echo '<br>';
    echo $file_type;
    echo '<br>';
    echo $file_ext;
    echo '<br>';


    $expensions= array("jpeg","jpg","png");

    if(in_array($file_ext,$expensions)=== false){
        $errors[]="Μόνο JPEG ή PNG file.";
    }

    if($file_size > 2097152){
        $errors[]='File size must be excately 2 MB';
    }

    if(empty($errors)==true){
        $path = $upload_dir.$file_name;
        echo $file_tmp.' >> '.$path;
        echo '<br>';

        //check the folder status _START
        if (!is_dir($upload_dir) || !is_writable($upload_dir)) {
            echo 'Upload directory('.$upload_dir.') is not writable, or does not exist.';
        }
        //_END

        if(move_uploaded_file($file_tmp, $upload_dir.$file_name)===TRUE) { 
            $logged_in_user_id = mysql_insert_id($db);
            $sql ="UPDATE users SET profile_image='$path' WHERE id='$id'";
            echo $sql;
            echo '<br>';


            $result = mysqli_query($db, $sql);

            echo "Success";    
        }
    }else{
        print_r($errors);
    }
}

Problem is in how you get the user ID for your insert:

$logged_in_user_id = mysql_insert_id($db)

mysql_insert_id($db) will get the ID of your last insert that generates an autoincrement. I do not believe it will work as intended if you have closed the connection after your insert. If your insert is on a different script, use sessions or $_GET or $_POST to transfer your user ID.

Also the reason could be incompatibility between packages:

you are using mysqli to write to db. but retrieving the last ID with mysql package. mysqli also has a method for this operation: mysqli_insert_id()

Also you get your user ID in to variable $logged_in_user_id but in your query you are using variable $id ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM