registered user upload image & store file path to MySQL

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • haribo48
    New Member
    • Mar 2012
    • 1

    registered user upload image & store file path to MySQL

    Hi

    I'm a beginner with PHP and MySQL and would like to add a function to a website that lets registered users upload an avatar picture of themselves and store the path in MySQL.

    Then have a page which displays back the correct image for whoever is logged in.

    I created 2 mySQL tables, users & images

    Users table fields - username (is PK), name, password
    images table fields - imageID (is PK), username (is FK) and imagePath.

    I run through online tutorials and have got an image upload working but i have problems

    1. if I upload 2 images with the same name i get an error so i think i need to rename each image to a random filename.

    2. displaying conect from the database for member currently logged in, both text and image. the online tutorial i echo'd the image but just got the path.

    If someone could explain how to write this code for this purpose, i use notepad++ i would very much like to learn php

    thanks you
  • johny10151981
    Top Contributor
    • Jan 2010
    • 1059

    #2
    for problem one:
    user name is unique i guess, if not then first suggestion make username unique. you can do a silly trick. Just save the image file same as user name. such as user johny, if user johny upload a file then rename the image file as johny.jpeg

    for problem 2:
    if you echo image path, it will display the path. for the browser the path is a simple text. To display the image you must have to follow the standard html rules related with img:
    a small example:
    Code:
    <img src='your_image_path_including_file_name_' alt='file missing'>

    Comment

    • PsychoCoder
      Recognized Expert Contributor
      • Jul 2010
      • 465

      #3
      Take a look at this, renaming your file should help stop duplicate file names.

      Upload and rename file

      If you didnt want to use their way of generating a random number then you can replace that with a GUID, which can look like so:

      Code:
      <?php
      function create_guid(){
          if (function_exists('com_create_guid')){
              return com_create_guid();
          }else{
              mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
              $id = strtoupper(md5(uniqid(rand(), true)));
              $hyphen = chr(45);// "-"
              $uuid = chr(123)// "{"
                      .substr($id, 0, 8).$hyphen
                      .substr($id, 8, 4).$hyphen
                      .substr($id,12, 4).$hyphen
                      .substr($id,16, 4).$hyphen
                      .substr($id,20,12)
                      .chr(125);// "}"
              return $uuid;
          }
      }
      echo guid();
      ?>
      Hope that helps :)

      Comment

      Working...