multiple file upload to server and MySQL database

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • johngault
    New Member
    • Dec 2008
    • 5

    #1

    multiple file upload to server and MySQL database

    I've been working with this PHP page for several days now and I'm stumped. The page is supposed to allow the user to upload up to six images for their profile. When the user adds an image it (the page coding) does verify file size, if correct it places it on the server in the users folder and with the correct names and extension, creates the thumbnail and adds the correlating file name. However, it only adds the first file name to the database. When it displays the images we see the six columns in the table, but of course only the first column contains an image because the other image names did not get written into the database table. Does anyone see what is written wrong or missing? please!

    [code=php]
    <? if (!isset($_COOKI E["id"]) || $_COOKIE['usertype']!="chatmodels " )

    {

    header("locatio n: ../../login.php");

    } else{

    include("../../dbase.php");

    $result=mysql_q uery("SELECT user from $_COOKIE[usertype] WHERE id='$_COOKIE[id]' LIMIT 1");


    while($row = mysql_fetch_arr ay($result))

    { $username=$row[user]; }

    }
    mysql_free_resu lt($result);

    $errorMsg="You can upload up to 6 images";



    //function that handles creation of thumbnails

    function LoadJpeg ($imgname,$tocr eate) {

    $tnsize="80";//thumbnail size

    $bigimage = @ImageCreateFro mJPEG ($imgname); // Attempt to open

    if (!$bigimage){

    $result=false;

    echo "<font color=#ffdd54>T he image thumbnail could not be created. The image file might be corrupted.</font><br> You can can resave the file by using any image editor and then try again<br><br>Th ank You! $endstr ";

    //exit();

    }

    $tnimage = ImageCreate($tn size,$tnsize);

    $white = ImageColorAlloc ate ($tnimage,0, 0, 0);

    $sz = GetImageSize($i mgname);

    // load our internal variables

    $x = $sz[0]; // big image width

    $y = $sz[1]; // big image height



    // find the larger dimension

    if ($x>$y) { // if it is the width then

    $dx = 0; // the left side of the new image

    $w = $tnsize; // the width of the new image

    $h = ($y / $x) * $tnsize; // the height of the new image

    $dy = ($tnsize - $h) / 2; // the top of the new image

    }else{ // if the height is larger then

    $dy = 0; // the top of the new image

    $h = $tnsize; // the height of the new image

    $w = ($x / $y) * $tnsize; // the width of the new image

    $dx = ($tnsize - $w) / 2; // the left edgeof the new image

    }

    // copy the resized version into the thumbnal image

    ImageCopyResize d($tnimage, $bigimage, $dx, $dy, 0, 0, $w, $h, $x, $y);

    //if we manage to create the thumbnail

    if (ImageJPEG($tni mage,$tocreate, 80) && $x<640 && $y<640){

    $result=true;

    } else{ //if we dont

    $result=false;

    if ($x>640 || $y>640){

    $errorMsg="File resolution too big. Maximum 640x640 pictures accepted.";

    } else{

    $errorMsg="Thum bnail file could not be created";

    }

    //exit();

    }

    return $result;

    }

    if(!isset($_COO KIE["id"]))

    {

    header("Locatio n: ../../login.php");

    } else if (isset($_FILES['ImageFile']['tmp_name']))

    {

    $currentTime=ti me();

    $pictureName=md 5("$currentTime ".$_SERVER['REMOTE_ADDR']);



    $urlImage="../../models/".$username ."/".$pictureName. ".jpg";

    $urlThumbnail=" ../../models/".$username ."/".$pictureName. "_thumbnail.jpg ";





    //we copy the thumbail image

    if (copy ($_FILES['ImageFile']['tmp_name'],$urlImage) && LoadJpeg($urlIm age,$urlThumbna il))

    {

    $id=$_COOKIE["id"];

    mysql_query("IN SERT INTO modelpictures ( user , name, dateuploaded ) VALUES ('$username', '$pictureName', '$currentTime') ");

    $errorMsg.='<im g src="http://bytes.com/topic/models/'.$username.'/'.$pictureName. '_thumbnail.jpg "> File Copied';

    }

    else

    {

    $errorMsg.="Fil e not Copied. Check resolution. Maximum 640kb files accepted.";

    }

    } else if(isset($_GET[delete]))

    {

    unlink("../../models/$username/$_GET[delete]_thumbnail.jpg" );

    unlink("../../models/$username/$_GET[delete].jpg");

    mysql_query('DE LETE from modelpictures WHERE name="'.$_GET[delete].'" LIMIT 1');

    $errorMsg+="Fil e Deleted";

    }


    ?>

    <?
    include("_model s.header.php");
    ?>
    <br>

    <span style="font-weight: bold">This function is still under development process. Currently you can upload 1 image only!</span>
    <table width="720" border="0" align="center" cellpadding="0" cellspacing="0" >

    <tr valign="top">

    <td height="113"><f orm action="uploadp icture.php" method="post" enctype="multip art/form-data" name="form2">

    <p><span class="error">

    <?php if ( isset($errorMsg ) && $errorMsg!=""){ echo $errorMsg; } ?>

    </span></p>

    <table width="720" border="0" align="center" cellpadding="4" cellspacing="0" >

    <tr class="barbg">

    <td colspan="2"><sp an class="form_hea der_title">Uplo ad new Image </span></td>
    </tr>

    <tr align="right">

    <td width="555" align="left"><i nput name="ImageFile " type="file" id="ImageFile" >

    <input type="submit" name="Submit2" value="Upload image to my gallery"></td>

    </tr>

    </table>

    <br>

    <table width="720" border="0" align="center" cellpadding="4" cellspacing="0" >

    <tr class="barbg">

    <td class="barbg">< span class="form_hea der_title">Imag e Gallery </span></td>

    </tr>

    <tr>

    <td>

    <table width="700" border="1" align="center" bordercolor="#C CCCCC">

    <?

    $count=0;

    $result = mysql_query('SE LECT * FROM modelpictures WHERE user="'.$userna me.'" ORDER BY dateuploaded DESC');

    while($row = mysql_fetch_arr ay($result))

    {

    $count++;

    if ($count>0) {echo"<tr>";}

    echo "<td width='100'clas s='form_definit ions' height='100' align='center' valign='middle' ><img src ='../../models/".$username ."/".$row[name]."_thumbnail.jp g' ><br><a href='uploadpic ture.php?delete =$row[name]'>Delete</a></td>";

    if ($count==6){ echo"</tr>"; $count=0;}

    }

    mysql_free_resu lt($result);

    for($i=0; $i<6-$count; $i++)

    {

    echo"<td width='100' height='100' align='center' valign='middle' >&nbsp</td>";

    }

    echo"</tr>";

    ?>

    </table></td>

    </tr>

    </table>

    </form></td>

    </tr>

    <tr>

    <td>&nbsp;</td>

    </tr>

    </table>[/code]
    Last edited by pbmods; Dec 30 '08, 02:57 AM. Reason: Added CODE tags.
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hi.

    On line #145. You execute the query to add the new image to the database, but there is nothing in place to check whether the row was actually added. All errors that could be occurring would simply be ignored.

    Make sure that query is in fact working before you do anything else.
    (See Turn on PHP Debugging Messages to see how to do that)

    Comment

    • johngault
      New Member
      • Dec 2008
      • 5

      #3
      Thank you for your patience.
      I added the error checking and found a warning on line 241, undefined constant assumed 'name'.
      So I added $name=$row["name"]; in line 234 and changed line 241 to:
      [code=php]echo "<td width='100'clas s='form_definit ions' height='100' align='center' valign='middle' ><img src ='../../models/".$username ."/".$name."_thumb nail.jpg' ><br><a href='uploadpic ture.php?delete =$name'>Delete</a></td>";[/code]

      I see no further warnings or errors. I can upload 1 image (file name) successfully to the sql table and display that 1 image. Uploading additional image files will add to the server folder, but not the sql table.
      Last edited by pbmods; Dec 31 '08, 12:30 AM. Reason: Added CODE tags.

      Comment

      • Atli
        Recognized Expert Expert
        • Nov 2006
        • 5062

        #4
        And did the query in line #145 get executed successfully every time?

        To make sure of that, try something like:
        [code=php]
        $sql = "INSERT INTO ...";
        $result = mysql_query($sq l)
        or die("<h3>Query failed!</h3><pre>". mysql_error() ."</pre>");

        if(mysql_get_af fected_rows($re sult) != 1) {
        die("<h3>Failed to insert!</h3><pre>". mysql_error() ."</pre>");
        }[/code]
        That should tell you why the row isn't getting inserted.

        Comment

        • johngault
          New Member
          • Dec 2008
          • 5

          #5
          Adding/changing line 145 with the above resulted in:
          Query failed!
          Duplicate entry 'Username' for key 1

          Comment

          • johngault
            New Member
            • Dec 2008
            • 5

            #6
            Since the primary key in the Sql table is the Username, the subsequent images beyond the first do not get added to the table because Sql will not allow more than one Unique entry to the primary key. Nice what reading errors and warnings can trigger in the grey matter! :) So -- by adding a check at the beginning of the process to verify if the Username already exists in the table and if not create it and than removing the insert 'user' from line 145 allows Sql to do what we expect it to do.

            Comment

            • Atli
              Recognized Expert Expert
              • Nov 2006
              • 5062

              #7
              Ahh ok. So the username is the primary key.
              Then there is no good way to add multiple pictures per user, using your current table structure.
              If you simply remove the 'user' field from the INSERT clause, then you will just have a bunch of images floating around without a user.

              But, if you add a integer field to your current structure and make that your primary key, you can use your code just as it is.

              I mean, if you table looked somewhat like:
              Code:
              modelpicture
              ----------------
              id int unsigned primary key
              user varchar not null
              image varchar not null
              created datetime not null
              The 'id' field would act as a row counter of sorts, just what a PK is usually supposed to be.

              Comment

              • johngault
                New Member
                • Dec 2008
                • 5

                #8
                Perfect. That solution was right on. I had to make the id primary key auto increment to get past the duplicate value error from Sql.
                Thank you for your help. Awesome!

                Comment

                • Atli
                  Recognized Expert Expert
                  • Nov 2006
                  • 5062

                  #9
                  I'm glad I was able to help :)

                  Comment

                  Working...