Storing Data in Mysql Database

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Shakes746
    New Member
    • May 2014
    • 4

    Storing Data in Mysql Database

    Hello, I'm working on a website that will need to store data like pdf documents and doc documents in mqsql database without storing them in a file Like the code below. I need help with the php code and mysql code to use.


    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('127.0.0.1', 'user', 'pwd', 'myTable');
            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.html">here</a> to go back</p>';
    ?>
    Last edited by Rabbit; May 27 '14, 05:35 AM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • Luuk
    Recognized Expert Top Contributor
    • Mar 2012
    • 1043

    #2
    Could you give more details on:
    What is going wrong?

    Comment

    • Shakes746
      New Member
      • May 2014
      • 4

      #3
      Well i'm a newbie to php. I'm Teaching myself for a school project. I needed to know if there was any other code i could use apart from the code given above. I tried it some weeks ago but was getting errors. I was following the comments made on the errors for the first code that was posted but still ended up with errors.

      Comment

      • Luuk
        Recognized Expert Top Contributor
        • Mar 2012
        • 1043

        #4
        "but was getting errors"
        I you have error, please add them to this request.

        Or should we try the code, and find other errors?

        What errors did you have, and which of them where you not able to solve? (and how did you try to solve them)

        "but still ended up with errors."
        Yes , but which errors? ;)

        Comment

        • Shakes746
          New Member
          • May 2014
          • 4

          #5
          This is how far i have gone-


          Code:
          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
          <html xmlns="http://www.w3.org/1999/xhtml">
          <head>
          <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
          
          	  <title>Admin Panel</title>
                 </head>
                 <body>
          	   <form method="post" enctype="multipart/form-data">
          <table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
          <tr>
          <td width="246">
          <input type="hidden" name="MAX_FILE_SIZE" value="2000000">
          <input name="userfile" type="file" id="userfile">
          </td>
          <td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
          </tr>
          </table>
          </form>
          	   
          	   
          	   
          	   
          	   <body>
          	   
          		  </body>
          	   </html>
                 
          
          
          
          
              <?php
              # Make sure an ID was passed
              if(isset($_GET['id']))
              {
              # Get the ID
              $id = $_GET['id'];
               
              # Make sure the ID is in fact a valid ID
              if(!is_numeric($id) || ($id <= 0)) {
              die("The ID is invalid!");
              }
               
              # Connect to the database
              $dbLink = mysql_connect("localhost", "root", "") or die (mysql_error());
              mysql_select_db("contents", $dbLink) or die(mysql_error());
               
              # Fetch the file information
              $query = "
              SELECT FileMime, FileName, FileSize, FileData
              FROM filestorage
              WHERE FileID = {$id}";
               
              $result = @mysql_query($query,$dbLink)
              or die("Error! Query failed: <pre>". mysqli_error($dbLink) ."</pre>");
               
              # Make sure the result is valid
              if(mysql_num_rows($result) == 1)
              {
              # Get the row
              $row = mysql_fetch_assoc($result);
               
              # Print headers
              header("Content-Type:".$row['FileMime']);
              header("Content-Length:".$row['FileSize']);
              header("Content-Disposition:attachment;filename=".$row['FileName']);
               
              # Print data
              echo $row['FileData'];
              }
              else
              {
              echo "Error! No image exists with that ID.";
              }
               
              # Free the mysqli resources
              @mysql_free_result($result);
              @mysql_close($dbLink);
               
              }
              else
              {
              echo "Error! No ID was passed.";
              }
              ?>
          
          
          </body>
          </html>
          The error i'm getting is "ERROR ! No Id passed" no matter how much i try to change the code it gives me that error. I also changed the upload form as well.
          Last edited by Rabbit; May 28 '14, 12:24 AM. Reason: Second warning: Please use [code] and [/code] tags when posting code or formatted data.

          Comment

          • Luuk
            Recognized Expert Top Contributor
            • Mar 2012
            • 1043

            #6
            Your form (line#9) does do a 'POST',
            line#35 is looking at '$_GET' toe get the value for ID

            Maybe you should Google something about the difference between POST and GET
            (hint: look here)

            Comment

            • Shakes746
              New Member
              • May 2014
              • 4

              #7
              Thanks for the link to the site it was very helpful.

              Comment

              Working...