Hello. I am making a register/login function, and i want the user to be able to upload files to his account, and can later view these files.

I wonder how i can make the upload script insert data in a mysql table only for the current user uploading, i dont want every file to be stuck at one table regardless which user is uploading. I hope i make myself clear.

Lets say you had a image host website. And the users could create albums and upload images to them. What did you do to let the user upload private files to their MySQL Table, in the script?

How do i proceed with this?

Here is some of my codes if that help you to understand;

add_file.php

<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
    // Make sure the file was sent without errors
    if($_FILES['uploaded_file']['error'] == 0) {
        // Connect to the database
        $dbLink = new mysqli('xxxxx', 'xxxxx', 'xxxxx', 'xxxxx');
        if(mysqli_connect_errno()) {
            die("MySQL connection failed: ". mysqli_connect_error());
        }
 
        // Gather all required data
        $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
        $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
        $data = $dbLink->real_escape_string(file_get_contents($_FILES  ['uploaded_file']['tmp_name']));
        $size = intval($_FILES['uploaded_file']['size']);
 
        // Create the SQL query
        $query = "
            INSERT INTO `file` (
                `name`, `mime`, `size`, `data`, `created`
            )
            VALUES (
                '{$name}', '{$mime}', {$size}, '{$data}', NOW()
            )";
 
        // Execute the query
        $result = $dbLink->query($query);
 
        // Check if it was successfull
        if($result) {
            echo 'Success! Your file was successfully added!';
        }
        else {
            echo 'Error! Failed to insert the file'
               . "<pre>{$dbLink->error}</pre>";
        }
    }
    else {
        echo 'An error accured while the file was being uploaded. '
           . 'Error code: '. intval($_FILES['uploaded_file']['error']);
    }
 
    // Close the mysql connection
    $dbLink->close();
}
else {
    echo 'Error! A file was not sent!';
}
 
// Echo a link back to the main page
echo '<p>Click <a href="index.php">here</a> to go back!</p>';
?>

upload.php

<!DOCTYPE html>
<head>
    <title>MySQL file upload example</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
    <form action="index.php?page=add_file" method="post" enctype="multipart/form-data">
        <input type="file" name="uploaded_file"><br>
        <input type="submit" value="Upload file">
    </form>
    <p>
        <a href="index.php?page=list_files">See all files</a>
    </p>
</body>
</html>

I want the user uploading the file, to upload it with his own "id"

For you requirements it sounds like you want a separate table for each user. Although I'm not sure if this is the most efficient option.

Perhaps you could add a field on your table to hold user_id which would reference your users table using foriegn/primary keys. Then you could use a SELECT where user_id='blah blah'.

Otherwise to do it your way, just create a 'files' table for each user upon registration. Call the table name $user_id.'files' (that variable can come from $_POST or your session variables. Then you can use $query = "SELECT * from ".$user_id."files;" in your code that recalls the data.

create userid to your file table to make a unique file to the user.

also i suggest to you, do not put your file in your dbase it will get bigger and hard to load someday/somehow, create a folder to upload all of your files there. delete this code and delete the data entity to your database

$data = $dbLink->real_escape_string(file_get_contents($_FILES ));

try this code.

<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
    // Make sure the file was sent without errors
    if($_FILES['uploaded_file']['error'] == 0) {
        // Connect to the database
        $dbLink = new mysqli('xxxxx', 'xxxxx', 'xxxxx', 'xxxxx');
        if(mysqli_connect_errno()) {
            die("MySQL connection failed: ". mysqli_connect_error());
        }
 
$target = "images/"; 
$target = $target . basename( $_FILES['uploaded_file']['name']); 
        // Gather all required data
        $userid = $_SESSION['id']; //login session
        $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
        $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
     // delete this line   $data = $dbLink->real_escape_string(file_get_contents($_FILES  ['uploaded_file']['tmp_name']));
        $size = intval($_FILES['uploaded_file']['size']);
 
        // Create the SQL query
       //add userid to your database delete the data entity.
        $query = "
            INSERT INTO `file` (
              `userid`,  `name`, `mime`, `size`, `created`
            )
            VALUES ('{$userid}',
                '{$name}', '{$mime}', {$size}, NOW()
            )";
 
        // Execute the query
        $result = $dbLink->query($query);
 
        // Check if it was successfull
        if($result) {
            move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target);
            echo 'Success! Your file was successfully added!';
        }
        else {
            echo 'Error! Failed to insert the file'
               . "<pre>{$dbLink->error}</pre>";
        }
    }
    else {
        echo 'An error accured while the file was being uploaded. '
           . 'Error code: '. intval($_FILES['uploaded_file']['error']);
    }
 
    // Close the mysql connection
    $dbLink->close();
}
else {
    echo 'Error! A file was not sent!';
}
 
// Echo a link back to the main page
echo '<p>Click <a href="index.php">here</a> to go back!</p>';
?>

create userid to your file table to make a unique file to the user.

also i suggest to you, do not put your file in your dbase it will get bigger and hard to load someday/somehow, create a folder to upload all of your files there. delete this code and delete the data entity to your database

$data = $dbLink->real_escape_string(file_get_contents($_FILES ));

try this code.

<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
    // Make sure the file was sent without errors
    if($_FILES['uploaded_file']['error'] == 0) {
        // Connect to the database
        $dbLink = new mysqli('xxxxx', 'xxxxx', 'xxxxx', 'xxxxx');
        if(mysqli_connect_errno()) {
            die("MySQL connection failed: ". mysqli_connect_error());
        }
 
$target = "images/"; 
$target = $target . basename( $_FILES['uploaded_file']['name']); 
        // Gather all required data
        $userid = $_SESSION['id']; //login session
        $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
        $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
     // delete this line   $data = $dbLink->real_escape_string(file_get_contents($_FILES  ['uploaded_file']['tmp_name']));
        $size = intval($_FILES['uploaded_file']['size']);
 
        // Create the SQL query
       //add userid to your database delete the data entity.
        $query = "
            INSERT INTO `file` (
              `userid`,  `name`, `mime`, `size`, `created`
            )
            VALUES ('{$userid}',
                '{$name}', '{$mime}', {$size}, NOW()
            )";
 
        // Execute the query
        $result = $dbLink->query($query);
 
        // Check if it was successfull
        if($result) {
            move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target);
            echo 'Success! Your file was successfully added!';
        }
        else {
            echo 'Error! Failed to insert the file'
               . "<pre>{$dbLink->error}</pre>";
        }
    }
    else {
        echo 'An error accured while the file was being uploaded. '
           . 'Error code: '. intval($_FILES['uploaded_file']['error']);
    }
 
    // Close the mysql connection
    $dbLink->close();
}
else {
    echo 'Error! A file was not sent!';
}
 
// Echo a link back to the main page
echo '<p>Click <a href="index.php">here</a> to go back!</p>';
?>

Thanks allot for the reply mate.
The changes you made helped me allot for my 2th upload function.
But i still need to have the database upload for this one.
I edited my post, please have a look at the tables.

Seems like i could not edit my post..

Here is what my SQL Database looks like.

Tables;
login
file

file;
id (INT(11)) a_i Primary
name varchar (60)
mime varchar(50)
size bigint(20)
data mediumblob) Binary
created datetime)

login
loginid int(20) a_i Primary
username varchar(30)
password varchar(50)
email varchar(255)
actcode varchar(45)
disabled tinyint(1)
activated tinyint(1)

What do i do to make the user who upload a file, also upload an unique file id so he later can view all his uploaded files? look at top for my current script

i have 1 question for you.

can user download and share the file?

if you say yes

here is your code:

<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
    // Make sure the file was sent without errors
    if($_FILES['uploaded_file']['error'] == 0) {
        // Connect to the database
        $dbLink = new mysqli('xxxxx', 'xxxxx', 'xxxxx', 'xxxxx');
        if(mysqli_connect_errno()) {
            die("MySQL connection failed: ". mysqli_connect_error());
        }
 $userid = $_SESSION['id']; //login session
$target = "images/".$userid."_"; 
$target = $target . basename( $_FILES['uploaded_file']['name']); 
        // Gather all required data
        
        $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
        $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
     // delete this line   $data = $dbLink->real_escape_string(file_get_contents($_FILES  ['uploaded_file']['tmp_name']));
        $size = intval($_FILES['uploaded_file']['size']);
 
        // Create the SQL query
       //add userid to your database delete the data entity.
        $query = "
            INSERT INTO `file` (
              `userid`,  `name`, `mime`, `size`, `created`
            )
            VALUES ('{$userid}',
                '{$name}', '{$mime}', {$size}, NOW()
            )";
 
        // Execute the query
        $result = $dbLink->query($query);
 
        // Check if it was successfull
        if($result) {
            move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target);
            echo 'Success! Your file was successfully added!';
        }
        else {
            echo 'Error! Failed to insert the file'
               . "<pre>{$dbLink->error}</pre>";
        }
    }
    else {
        echo 'An error accured while the file was being uploaded. '
           . 'Error code: '. intval($_FILES['uploaded_file']['error']);
    }
 
    // Close the mysql connection
    $dbLink->close();
}
else {
    echo 'Error! A file was not sent!';
}
 
// Echo a link back to the main page
echo '<p>Click <a href="index.php">here</a> to go back!</p>';
?>

if you say no just add userid to your file.

to view all of his file

<table cellpadding="0" cellspacing="0" border="1">
       <tr>
       <th bgcolor="black" width="150"><p><font color="white">File Name</font></p></th>
       <th bgcolor="black" width="150"><p><font color="white">Date Uploaded</font></p></th>
        </tr>
        <?php 
           $id = $_SESSION['id']; // login session.
	   $sql = "Select * from file where userid='$id'";
	   
	   $result = mysql_query($sql);
	   
	   while($row = mysql_fetch_assoc($result)) {
	   ?>
       <tr>
       
       <td><p><font color="#000099"><?php echo $row['name']; ?></font></p></td>
       <td><p><?php echo $row['created']; ?></p></td>
       </tr>
        <?php
	   }
	   ?>
       </Table>
commented: Insane speed with solving problems! +0

i have 1 question for you.

can user download and share the file?

if you say yes

here is your code:

<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
    // Make sure the file was sent without errors
    if($_FILES['uploaded_file']['error'] == 0) {
        // Connect to the database
        $dbLink = new mysqli('xxxxx', 'xxxxx', 'xxxxx', 'xxxxx');
        if(mysqli_connect_errno()) {
            die("MySQL connection failed: ". mysqli_connect_error());
        }
 $userid = $_SESSION['id']; //login session
$target = "images/".$userid."_"; 
$target = $target . basename( $_FILES['uploaded_file']['name']); 
        // Gather all required data
        
        $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
        $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
     // delete this line   $data = $dbLink->real_escape_string(file_get_contents($_FILES  ['uploaded_file']['tmp_name']));
        $size = intval($_FILES['uploaded_file']['size']);
 
        // Create the SQL query
       //add userid to your database delete the data entity.
        $query = "
            INSERT INTO `file` (
              `userid`,  `name`, `mime`, `size`, `created`
            )
            VALUES ('{$userid}',
                '{$name}', '{$mime}', {$size}, NOW()
            )";
 
        // Execute the query
        $result = $dbLink->query($query);
 
        // Check if it was successfull
        if($result) {
            move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target);
            echo 'Success! Your file was successfully added!';
        }
        else {
            echo 'Error! Failed to insert the file'
               . "<pre>{$dbLink->error}</pre>";
        }
    }
    else {
        echo 'An error accured while the file was being uploaded. '
           . 'Error code: '. intval($_FILES['uploaded_file']['error']);
    }
 
    // Close the mysql connection
    $dbLink->close();
}
else {
    echo 'Error! A file was not sent!';
}
 
// Echo a link back to the main page
echo '<p>Click <a href="index.php">here</a> to go back!</p>';
?>

if you say no just add userid to your file.

to view all of his file

<table cellpadding="0" cellspacing="0" border="1">
       <tr>
       <th bgcolor="black" width="150"><p><font color="white">File Name</font></p></th>
       <th bgcolor="black" width="150"><p><font color="white">Date Uploaded</font></p></th>
        </tr>
        <?php 
           $id = $_SESSION['id']; // login session.
	   $sql = "Select * from file where userid='$id'";
	   
	   $result = mysql_query($sql);
	   
	   while($row = mysql_fetch_assoc($result)) {
	   ?>
       <tr>
       
       <td><p><font color="#000099"><?php echo $row['name']; ?></font></p></td>
       <td><p><?php echo $row['created']; ?></p></td>
       </tr>
        <?php
	   }
	   ?>
       </Table>

ryan311 you are my hero! Thank you so much for this help, i got what i need now.
i'll send you a Pm in the future when my site is done, might not be a insane site, but i'm learning.

Sincerely,
Sorcher

i have 1 question for you.

can user download and share the file?

if you say yes

here is your code:

<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
    // Make sure the file was sent without errors
    if($_FILES['uploaded_file']['error'] == 0) {
        // Connect to the database
        $dbLink = new mysqli('xxxxx', 'xxxxx', 'xxxxx', 'xxxxx');
        if(mysqli_connect_errno()) {
            die("MySQL connection failed: ". mysqli_connect_error());
        }
 $userid = $_SESSION['id']; //login session
$target = "images/".$userid."_"; 
$target = $target . basename( $_FILES['uploaded_file']['name']); 
        // Gather all required data
        
        $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
        $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
     // delete this line   $data = $dbLink->real_escape_string(file_get_contents($_FILES  ['uploaded_file']['tmp_name']));
        $size = intval($_FILES['uploaded_file']['size']);
 
        // Create the SQL query
       //add userid to your database delete the data entity.
        $query = "
            INSERT INTO `file` (
              `userid`,  `name`, `mime`, `size`, `created`
            )
            VALUES ('{$userid}',
                '{$name}', '{$mime}', {$size}, NOW()
            )";
 
        // Execute the query
        $result = $dbLink->query($query);
 
        // Check if it was successfull
        if($result) {
            move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target);
            echo 'Success! Your file was successfully added!';
        }
        else {
            echo 'Error! Failed to insert the file'
               . "<pre>{$dbLink->error}</pre>";
        }
    }
    else {
        echo 'An error accured while the file was being uploaded. '
           . 'Error code: '. intval($_FILES['uploaded_file']['error']);
    }
 
    // Close the mysql connection
    $dbLink->close();
}
else {
    echo 'Error! A file was not sent!';
}
 
// Echo a link back to the main page
echo '<p>Click <a href="index.php">here</a> to go back!</p>';
?>

if you say no just add userid to your file.

to view all of his file

<table cellpadding="0" cellspacing="0" border="1">
       <tr>
       <th bgcolor="black" width="150"><p><font color="white">File Name</font></p></th>
       <th bgcolor="black" width="150"><p><font color="white">Date Uploaded</font></p></th>
        </tr>
        <?php 
           $id = $_SESSION['id']; // login session.
	   $sql = "Select * from file where userid='$id'";
	   
	   $result = mysql_query($sql);
	   
	   while($row = mysql_fetch_assoc($result)) {
	   ?>
       <tr>
       
       <td><p><font color="#000099"><?php echo $row['name']; ?></font></p></td>
       <td><p><?php echo $row['created']; ?></p></td>
       </tr>
        <?php
	   }
	   ?>
       </Table>

Sorry, but i removed the ¨data¨ entity and renamed "id" in the table "file" to "userid"
It says it completed the upload but no file is inserting into the folder.

//add userid to your database delete the data entity.
        $query = "
            INSERT INTO `file` (
              `userid`,  `name`, `mime`, `size`, `created`
            )
            VALUES ('{$userid}',
                '{$name}', '{$mime}', {$size}, NOW()
            )";

I suppose i was ment to rename the ïd¨ in "file" to "userid" since i cant have 2 INT's in same table.
Any idea why it wont insert?

no, don't rename or delete the id in your file because that is the unique file you need that in downloading or sharing a file. just add userid entity into your file

so here is the entity of your file table

-id /auto_increment
-userid /userid
-name / file name
-mime / file type
-size / file size
-created

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.