Uploading files into a MySQL database using PHP

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • granthought
    New Member
    • Dec 2013
    • 1

    thanks! this is very helpful. =)

    Comment

    • ucman123
      New Member
      • Dec 2013
      • 1

      hi,

      when I download file, there is entire html code in my download file. My code is same as in article above so I don't know where the problem would be, so please help.

      Comment

      • rsoni
        New Member
        • Mar 2014
        • 1

        Thank you so much...!!

        Comment

        • ahmad233
          New Member
          • Mar 2014
          • 5

          pls i got dis error "Got a packet bigger than 'max_allowed_pa cket' bytes," wat can i do

          Comment

          • Atli
            Recognized Expert Expert
            • Nov 2006
            • 5062

            MySQL limits the max size of packets it can receive, using the max_allowed_pac ket directive. Depending on your server version, it can be either 1MB or 4MB by default.

            If you want to submit binary files larger than that, you need to change this to a higher value in your MySQL server's configuration file. How exactly you do that depends on your platform. I suggest you use Google to find that out; it's a common question that has already been answered a few thousand times out there.

            Comment

            • ahmad233
              New Member
              • Mar 2014
              • 5

              i have change the default max_packet_allo wed to 128mbbut still received same error

              Comment

              • jakai
                New Member
                • Mar 2014
                • 1

                Sir, In get_file.php i got this error The ID is invalid!

                Comment

                • RiderRay2050
                  New Member
                  • Apr 2014
                  • 1

                  hey atil , bro u helped a lot .... the files in the database are viewing i.e working well till #53 but error is coming in the download part....i.e after #56
                  it always show no ID was passed
                  Code:
                   <?php
                      // Connect to the database
                  	//mysql_connect(""localhost","root",""") = $dblink   
                  	$dbLink = new mysqli("localhost", "root", "", 'iitm');
                      if(mysqli_connect_errno()) {
                          die("MySQL connection failed: ". mysqli_connect_error());
                      }
                       
                      // Query for a list of all existing files
                      $sql = 'SELECT `file_id`, `file_name` FROM `files`';
                      $result = $dbLink->query($sql);
                       
                      // Check if it was successfull
                      if($result) {
                          // Make sure there are some files in there
                          if($result->num_rows == 0) {
                              echo '<p>There are no files in the database</p>';
                          }
                          else {
                              // Print the top of a table
                              echo '<table width="100%">
                                      <tr>
                                          <td><b>Name</b></td>
                                     
                                       
                                      </tr>';
                       
                              // Print each file
                              while($row = $result->fetch_assoc()) {
                                  echo "
                                      <tr>
                                          <td>{$row['file_name']}</td>
                                          
                                          <td><a href='get_file.php?id={$row['file_id']}'>Download</a></td>
                                      </tr>";
                              }
                       
                              // Close table
                              echo '</table>';
                          }
                       
                          // Free the result
                          $result->free();
                      }
                      else
                      {
                          echo 'Error! SQL query failed:';
                          echo "<pre>{$dbLink->error}</pre>";
                      }
                       
                      // Close the mysql connection
                      $dbLink->close();
                      ?>
                  
                  
                  
                      <?php
                      // Make sure an ID was passed
                      if(isset($_GET['file_id'])) {
                      // Get the ID
                          $id = intval($_GET['file_id']);
                       
                          // Make sure the ID is in fact a valid ID
                          if($id <= 0) {
                              die('The ID is invalid!');
                          }
                          else {
                              // Connect to the database
                              $dbLink = new mysqli("localhost", "root", "", 'iitm');
                              if(mysqli_connect_errno()) {
                                  die("MySQL connection failed: ". mysqli_connect_error());
                              }
                       
                              // Fetch the file information
                              $query = "
                                  SELECT `name`
                                  FROM `files`
                                  WHERE `file_id` = {$id}";
                              $result = $dbLink->query($query);
                       
                              if($result) {
                                  // Make sure the result is valid
                                  if($result->num_rows == 1) {
                                  // Get the row
                                      $row = mysqli_fetch_assoc($result);
                       
                                      // Print headers
                                     while (@ob_end_clean());
                                      header("Content-Disposition: attachment; filename=". $row['file_name']);
                       
                                      // Print data
                                      echo $row['file'];
                                  }
                                  else {
                                      echo 'Error! No file exists with that ID.';
                                  }
                       
                                  // Free the mysqli resources
                                  @mysqli_free_result($result);
                              }
                              else {
                                  echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
                              }
                              @mysqli_close($dbLink);
                          }
                      }
                      else {
                          echo 'Error! No ID was passed.';
                      }
                      ?>

                  Comment

                  • Ravi Yadav
                    New Member
                    • Apr 2014
                    • 1

                    Finally Got after searching all websites in 2 days thank yu dude....

                    Comment

                    • thanhthupro
                      New Member
                      • May 2014
                      • 1

                      hello everyone can ask themselves how the images from the database to the screen from the addition of database files his (her) Atli

                      Comment

                      • jumper
                        New Member
                        • Jun 2014
                        • 1

                        <?php

                        // Make sure an ID was passed
                        if(isset($_GET['id'])) {
                        // Get the ID
                        $id = intval($_GET['id']);

                        // Make sure the ID is in fact a valid ID
                        if($id <= 0) {
                        die('The ID is invalid!');
                        }
                        else {
                        // Connect to the database
                        $dbLink = new mysqli("127.0.0 .1", "", "", "");
                        if(mysqli_conne ct_errno()) {
                        die("MySQL connection failed: ". mysqli_connect_ error());
                        }

                        // Fetch the file information
                        $query = "
                        SELECT `mime`, `name`, `size`, `data`
                        FROM `file`
                        WHERE `id` = {$id}";
                        $result = $dbLink->query($query );

                        if($result) {
                        // Make sure the result is valid
                        if($result->num_rows == 1) {

                        // Get the row
                        // $row = mysqli_num_rows ($result);

                        // Print headers
                        header("Content-Type: ". $row['mime']);
                        header("Content-Length: ". $row['size']);
                        header("Content-Disposition: attachment; filename=". $row['name']);
                        echo $name;
                        // Print data
                        echo $row['data'];
                        }
                        else {
                        echo 'Error! No image exists with that ID.';
                        }

                        // Free the mysqli resources
                        @mysqli_free_re sult($result);
                        }
                        else {
                        echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
                        }
                        @mysqli_close($ dbLink);
                        }
                        }
                        else {
                        echo 'Error! No ID was passed.';
                        }
                        ?>

                        Please help me to run this code GET FILES
                        I got an error

                        Error! No image exists with that ID.

                        Comment

                        • Atli
                          Recognized Expert Expert
                          • Nov 2006
                          • 5062

                          Have you made sure that the image actually does exist in the database?

                          Comment

                          • delvin
                            New Member
                            • Jun 2014
                            • 1

                            Hi Atli,

                            i'm using your code and it's working. but i have a probrem when i download the file and i open it, my file isn'n like before. now my file already convret with html tag.

                            how can i fix that?

                            Comment

                            • Djurres
                              New Member
                              • Aug 2014
                              • 4

                              Dear Atli,

                              Im using your code aswell, but I got a few problems.

                              The first file I upload there is no problem with, Its pasted in the DB, and I can download and see it on the files page.

                              After I uploaded the Second file I do get this error,

                              Error! No image exists with that ID.

                              If you want I can paste the code's here, but i copied these one on one, and the only things I did change are the tablenames, and I customized the login settings!

                              Thanks in advance :)

                              Comment

                              • Djurres
                                New Member
                                • Aug 2014
                                • 4

                                Just to be sure, Code's over here. I deleted my DB login files!

                                get_file.php
                                Code:
                                <?php
                                    // Make sure an ID was passed
                                    if(isset($_GET['id'])) {
                                    // Get the ID
                                        $id = intval($_GET['id']);
                                     
                                        // Make sure the ID is in fact a valid ID
                                        if($id <= 0) {
                                            die('The ID is invalid!');
                                        }
                                        else {
                                            // Connect to the database
                                            $dbLink = new mysqli('127.0.0.1', '', '', '');
                                            if(mysqli_connect_errno()) {
                                                die("MySQL connection failed: ". mysqli_connect_error());
                                            }
                                     
                                            // Fetch the file information
                                            $query = "
                                                SELECT `mime`, `name`, `size`, `data`
                                                FROM `filejtc`
                                                WHERE `id` = {$id}";
                                            $result = $dbLink->query($query);
                                     
                                            if($result) {
                                                // Make sure the result is valid
                                                if($result->num_rows == 1) {
                                                // Get the row
                                                    $row = mysqli_fetch_assoc($result);
                                     
                                                  //print headers
                                                    header("Content-Type: ". $row['mime']);
                                                    header("Content-Length: ". $row['size']);
                                                    header("Content-Disposition: attachment; filename=". $row['name']);
                                    
                                                    // Print data
                                                    echo $row['data'];
                                                }
                                                else {
                                                    echo 'Error! No image exists with that ID.';
                                                }
                                     
                                                // Free the mysqli resources
                                                @mysqli_free_result($result);
                                            }
                                            else {
                                                echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
                                            }
                                            @mysqli_close($dbLink);
                                        }
                                    }
                                    else {
                                        echo 'Error! No ID was passed.';
                                    }
                                    ?>
                                files.php
                                Code:
                                <?php
                                    // Connect to the database
                                    $dbLink = new mysqli('127.0.0.1', '', '', '');
                                    if(mysqli_connect_errno()) {
                                        die("MySQL connection failed: ". mysqli_connect_error());
                                    }
                                     
                                    // Query for a list of all existing files
                                    $sql = 'SELECT `id`, `name`, `mime`, `size`, `created` FROM `filejtc`';
                                    $result = $dbLink->query($sql);
                                     
                                    // Check if it was successfull
                                    if($result) {
                                        // Make sure there are some files in there
                                        if($result->num_rows == 0) {
                                            echo '<p>Er zitten nog geen bestanden in de database!</p>';
                                        }
                                        else {
                                            // Print the top of a table
                                            echo '<table width="100%">
                                                    <tr>
                                                        <td><b>Naam:</b></td>
                                                        <td><b>Soort bestand:</b></td>
                                                        <td><b>Grootte (bytes)</b></td>
                                                        <td><b>Aangemaakt</b></td>
                                                        <td><b>&nbsp;</b></td>
                                                    </tr>';
                                     
                                            // Print each file
                                            while($row = $result->fetch_assoc()) {
                                                echo "
                                                    <tr>
                                                        <td>{$row['name']}</td>
                                                        <td>{$row['mime']}</td>
                                                        <td>{$row['size']}</td>
                                                        <td>{$row['created']}</td>
                                                        <td><a href='get_file.php?id={$row['id']}'>Download</a></td>
                                                    </tr>";
                                            }
                                     
                                            // Close table
                                            echo '</table>';
                                        }
                                     
                                        // Free the result
                                        $result->free();
                                    }
                                    else
                                    {
                                        echo 'Error! SQL query failed:';
                                        echo "<pre>{$dbLink->error}</pre>";
                                    }
                                     
                                    // Close the mysql connection
                                    $dbLink->close();
                                    ?>
                                add_file.php
                                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('', '', '', '');
                                            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 `filejtc` (
                                                    `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 'Succes! Het bestand is toegevoegt aan de database!';
                                            }
                                            else {
                                                echo 'Error! Er is wat fout gegaan bij het invoegen aan de database! Probeer opnieuw!'
                                                   . "<pre>{$dbLink->error}</pre>";
                                            }
                                        }
                                        else {
                                            echo 'Er is wat fout gegaan tijdens het uploaden, probeer opnieuw! '
                                               . 'Error code: '. intval($_FILES['uploaded_file']['error']);
                                        }
                                     
                                        // Close the mysql connection
                                        $dbLink->close();
                                    }
                                    else {
                                        echo 'Error! Er is geen bestand geselecteerd!';
                                    }
                                     
                                    // Echo a link back to the main page
                                    echo '<p>Klik <a href="../jtc/files.php">HIER</a> om verder te gaan!</p>';
                                    ?>

                                Comment

                                Working...