Jump to content

Recommended Posts

I am able to send photos into the database table, no problem.  I guess now I would like info regarding how to send the actual picture file into a file folder on the server while sending the name of that same picture into the database table cell.  I think I can figure out the rest if I can get some guidance on how to approach this.  There are several (six) photos per stock number but may be as few as no photos per stock number. 

It is basically an auto inventory listed online with photos...

Here is the latest insert code I have been trying to get to work...and get errors on line 22..
// insert.php
Warning: Invalid argument supplied for foreach() in /home/inv/public_html/insert.php on line


// insert.php
<?php
//+-------------------------------------------------------------------------------------------
//| Check there are files to upload
//+-------------------------------------------------------------------------------------------

$stockid = $_POST['stockid'];
$stock = $_POST['stock'];
$year = $_POST['year'];
$make = $_POST['make'];
$model = $_POST['model'];
$price = $_POST['price'];
$miles = $_POST['miles'];

// You should do some validation here - look at the PHP String functions.

$files = $_FILES['files'];

$total_photos = 0;
$uploaded = 0;

foreach ($files['name'] as $key => $name)
{
    if ( ! empty($files['name'][$key]))
    {
        $total_photos++;
    }
}

if ($total_photos > 0)
{
    //+-------------------------------------------------------------------------------------------
    //| File Upload
    //+-------------------------------------------------------------------------------------------
    $path_to_photo_folder = '/home/username/public_html/uploads/photos/';

    $uploaded = 0;

    // TRY TO CREATE THE DIRECTORY (INCASE IT DOESN'T YET EXIST) ...
    $oldumask = umask(0);
    @ mkdir("$path_to_photo_folder",0777);
    umask($oldumask);

    foreach ($files['name'] as $key => $name)
    {
       $location = $path_to_photo_folder.$name.'.jpg';

          if ($files['size'][$key])
        {
            // If you want, you can allow only certain file-types
            if ($files['type'][$key] != 'image/jpeg' xor $files['type'][$key] != 'image/pjpeg' xor $files['type'][$key] != 'image/jpg')
            {
                // $feedback_msg = 'Only jpeg files are allowed to be uploaded!';
                // echo $feedback_msg;
                // exit;
            }

            // If you want, you can set a file size limit (in bytes)
            if ($files['size'][$key] > 500000)
            {
                // $feedback_msg = 'The size of each file must be less than 500kb.';
                // echo $feedback_msg;
                // exit;
            }

               if (is_uploaded_file($files['tmp_name'][$key]))
            {
                // This is the actual upload
                if ( ! @ move_uploaded_file($files['tmp_name'][$key], $location))
                {
                    // $feedback_msg = 'Problem: Could not move file to destination directory.';
                    // echo $feedback_msg;
                    // exit;
                }
                else
                {
                     $uploaded++;

                     //+--------------------------------------------------------------------------
                     //| Duplicate image and create a thumbnail
                     //+--------------------------------------------------------------------------
                     $size = getimagesize($location);

                     $width = $size[0];
                     $height = $size[1];

                     $src = imagecreatefromjpeg($location);
                     $dst = imagecreatetruecolor(200,200);

                     imagecopyresized($dst, $src, 0, 0, 0, 0, 200, 200, $width, $height); // You will lose parts of the image if it has a different aspect ratio than 1:1

                     imagejpeg($dst, "$path_to_file"."preview_$name.jpg", 85);

                     imagedestroy($dst);

                     //+--------------------------------------------------------------------------
                     //| Database Insert
                     //+--------------------------------------------------------------------------

                     function quote_smart($value)
                     {
                           // This function requires an active database connection to work...

                           if ( get_magic_quotes_gpc() )
                           {
                               $value = stripslashes($value);
                           }

                           // Quote if not a number or a numeric string
                        if ( ! is_numeric( $value ) || $value[0]=='0')
                           {
                               $value = mysql_real_escape_string($value);
                           }
                           else
                           {
                               return ( int ) $value;
                           }

                          return $value;
                     }

                     if ( ! ($conn = mysql_connect('localhost', 'db_username', 'db_password')))
                     {
                          // $feedback_msg = 'mysql_errno() . ' ' . mysql_error();
                          // echo $feedback_msg;
                          // exit;
                     }
                     else
                     {
                         mysql_select_db('database_name', $conn);

                         //+-------------------------------------------------
                         //| Protect from SQL injection
                         //+-------------------------------------------------
                         $stockid = quote_smart($stockid);
                         $stock = quote_smart($stock);
                         $year = quote_smart($year);
                         $make = quote_smart($make);
                         $model = quote_smart($model);
                         $price = quote_smart($price);
                         $miles = quote_smart($miles);

                         // Insert / Update ???
                         // $sql = "INSERT INTO inventory (stock, year, make, model, price, miles, photo{$uploaded}) VALUES ($stock, $year, $make, $model, $price, $miles, $location)";
                         // $sql = "UPDATE inventory SET stock=$stock, year=$year, make=$make, model=$model, price=$price, miles=$miles, photo{$uploaded}=$location WHERE id = $stockid";

                        if ( ! $res = mysql_query($sql))
                        {
                            echo "Could not update stock# $stock<br>SQL: $sql<br> Error: ".mysql_error();
                        }
                        else
                        {
                            echo "Stock# $stock Sucessfully updated<br>";
                        }
                     }
                 }
              }
        }
    }

    $uploaded > 1 ? $suffix = 'images were' : $suffix = 'image was';

    echo "$uploaded $suffix uploaded successfully.";

    echo 'Click <a href="stockmanage.php">HERE</a> to return to stock list</p>';
}
?> 



Link to comment
https://forums.phpfreaks.com/topic/30510-image-uploading-mysql-php-updated-issue/
Share on other sites

Your Form
[code]
<form action="insert.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td><strong>Single File Upload </strong></td>
</tr>
<tr>
<td>Select file
<input name="ufile" type="file" id="ufile" size="50" /></td>
</tr>
<tr>
<td align="center"><input type="submit" name="Submit" value="Upload" /></td>
</tr>
</table>
</td>
</form>
[/code]

Your Insert
[code]
<?php

//strip slashes
$name = stripslashes($name);

// Your file name you are uploading
$file_name = $HTTP_POST_FILES['ufile']['name'];

// random 4 digit to add to our file name
// some people use date and time in stead of random digit
$random_digit=rand(0000,9999);

//combine random digit to you file name to create new file name
//use dot (.) to combile these two variables

$new_file_name=$random_digit.$file_name;

//set where you want to store files
//in this example we keep file in folder upload
//$new_file_name = new upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "/your/directory/images1/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful Upload!<BR/><BR/>";



include "(connect.php)";

$query="insert into photos (id,username,file) VALUES ('$id','$mysite_username','$new_file_name')";
$result = MYSQL_QUERY($query);



}
else
{
echo "Error";
}
}
?>
[/code]
It keeps actually changing the number on line 11 of insert.php and causing an error...
From $random_digit to 897656 for example and causing an error...
like it's rewriting the php for insert.php.

This is a single file upload also...I just wanted to see if it worked.  I can't get it to work yet...

Thoughts?

Also, this adds only one photo...any way to add six at a time and have them all load and be associated with the same stock number?
Sorry, I gave you the wrong thing. This works with one upload, I'm sure it can be re-configured to do more than one.

Also, As long as your passing the the stock number to a database, you can associate every picture you want with the stock number.

FORM
[code]
<form enctype="multipart/form-data" action="insert.php" method="POST">
<table>
<tr>
<td>Please choose a file: </td>
<td><input name="uploaded" type="file" /></td>
</tr>
<tr>
  <td>Caption (optional)</td>
  <td><input name="caption" type="text" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><?
$button_text = array('Upload It','Are you sure you want to upload THAT picture?','Oh Man, that\'s going to be a good one!');
echo '<input type="submit" name="submit" value="' . $button_text[array_rand($button_text)] . '">'; ?>
</td>
</tr>
</table>
</form>
[/code]

INSERT
[code]
//This function separates the extension from the rest of the file name and returns it
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}

//This applies the function to our file
$ext = findexts ($_FILES['uploaded']['name']) ;
    //This line assigns a random number to a variable. You could also use a timestamp here if you prefer.
    $ran = rand () ;

    //This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended.
    $ran2 = $ran.".";

    //This assigns the subdirectory you want to save into... make sure it exists!
    $target = "/your/directory/images1/";

    //This combines the directory, the random file name, and the extension
    $target = $target . $ran2.$ext;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "<img src='http://www.fotobins.com/$username/$ran2$ext' width='100'><BR/>
<a href=http://www.fotobins.com/upload.php>Upload Another Photo</a>";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
include ("conncet");

$query="insert into photos (id,username,file,caption,share) VALUES ('$id','$username','$ran2$ext','$caption','No')";
$result = MYSQL_QUERY($query);
[/code]
What is the fotobins url about?

Also, this one has an error also.  Line 26

Also, I don't need any comment area, but thanks anyway.

I feel like if I can get one of these to work I can alter it to add the five other photos...

I changed my connection file to the correct one, added the php tags and changed the image folder to the correct one...no go...

Thanks...

[quote author=timmah1 link=topic=118473.msg484163#msg484163 date=1166030706]
Sorry, I gave you the wrong thing. This works with one upload, I'm sure it can be re-configured to do more than one.

Also, As long as your passing the the stock number to a database, you can associate every picture you want with the stock number.

FORM
[code]
<form enctype="multipart/form-data" action="insert.php" method="POST">
<table>
<tr>
<td>Please choose a file: </td>
<td><input name="uploaded" type="file" /></td>
</tr>
<tr>
  <td>Caption (optional)</td>
  <td><input name="caption" type="text" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><?
$button_text = array('Upload It','Are you sure you want to upload THAT picture?','Oh Man, that\'s going to be a good one!');
echo '<input type="submit" name="submit" value="' . $button_text[array_rand($button_text)] . '">'; ?>
</td>
</tr>
</table>
</form>
[/code]

INSERT
[code]
//This function separates the extension from the rest of the file name and returns it
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}

//This applies the function to our file
$ext = findexts ($_FILES['uploaded']['name']) ;
    //This line assigns a random number to a variable. You could also use a timestamp here if you prefer.
    $ran = rand () ;

    //This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended.
    $ran2 = $ran.".";

    //This assigns the subdirectory you want to save into... make sure it exists!
    $target = "/your/directory/images1/";

    //This combines the directory, the random file name, and the extension
    $target = $target . $ran2.$ext;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "<img src='http://www.fotobins.com/$username/$ran2$ext' width='100'><BR/>
<a href=http://www.fotobins.com/upload.php>Upload Another Photo</a>";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
include ("conncet");

$query="insert into photos (id,username,file,caption,share) VALUES ('$id','$username','$ran2$ext','$caption','No')";
$result = MYSQL_QUERY($query);
[/code]
[/quote]
Sorry about the url, this is the exact script that I use on my site (fotobins.com)

Your gettting an error on line 26 because of the url, just take it out

[code]
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "Succesful Upload!";
}
else
[/code]
I'd be appreciative to see the code.  Thanks.

[quote author=blacknight link=topic=118473.msg484123#msg484123 date=1166025276]
all that you have asked is possable using gd support to resize the image but gd only support some file types not all i think can post a script i use and you can alter it if you want
[/quote]
So...

I can insert a file (photo file) into the database, no problem.  I would like to see a demo of how to send the picture to a file folder, not the database...and the NAME of the photo in the database...

The associated issue is:  how do I resize the photo (jpeg) when uploading to the file so that all photos are stored as 200x200 pixels, for example.  That way, if there is an issue, it is noticed on upload, not download later...

Also, since each photo (six per stock number) is stored in a database with its name in a different cell in the database table, the stock association is no longer an issue...I kind of overthought that...thanks...

Any thoughts on the remaining problem are appreciated...Thanks!
Okee dokee...

As stated earlier, this is the insert file that does not have the features I would like...such as pictures uploaded to file folders instead of the database, picture resizing on upload...

So I guess the main issue now is that I would like info regarding how to send the picture itself into a file folder and the name of said picture into the database table...I think I can figure out the rest...or already have...

It seems like the code would be simple but everything I have tried won't work...thoughts are apprecaited. 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Done...</title>
</head>
<body>
<p>
<?php

//This is the correct code for inserting the data--the actual insertion via php--

//this is the connection to the database file
include "link.php";

$sql = "INSERT INTO `inventory` (`stock`, `year`, `make`, `model`, `price`, `miles`, `photo1`, `photo2`, `photo3`, `photo4`, `photo5`, `photo6`, `description`) VALUES ('".mysql_real_escape_string($_POST['stock'])."','".mysql_real_escape_string($_POST['year'])."','".mysql_real_escape_string($_POST['make'])."','".mysql_real_escape_string($_POST['model'])."','".mysql_real_escape_string($_POST['price'])."','".mysql_real_escape_string($_POST['miles'])."','".mysql_real_escape_string($_POST['photo1'])."','".mysql_real_escape_string($_POST['photo2'])."','".mysql_real_escape_string($_POST['photo3'])."','".mysql_real_escape_string($_POST['photo4'])."','".mysql_real_escape_string($_POST['photo5'])."','".mysql_real_escape_string($_POST['photo6'])."','".mysql_real_escape_string($_POST['description'])."')";
if($res = mysql_query($sql))
{
echo('one record added');
}
else
{
echo('There was a problem inserting data.');
}
?>
</body>
</html>


[quote author=DeathStar link=topic=118473.msg484799#msg484799 date=1166106320]
First time i see an upload script!!
LOL
[/quote]
I'm only using jpeg...so if that would work I'm happy to see the code and try to modify it to work...thanks.

[quote author=blacknight link=topic=118473.msg484123#msg484123 date=1166025276]
all that you have asked is possable using gd support to resize the image but gd only support some file types not all i think can post a script i use and you can alter it if you want
[/quote]
any thoughts on my updated question, first in thread?  Thanks...for all your help...

[quote author=timmah1 link=topic=118473.msg484181#msg484181 date=1166032090]
Sorry about the url, this is the exact script that I use on my site (fotobins.com)

Your gettting an error on line 26 because of the url, just take it out

[code]
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "Succesful Upload!";
}
else
[/code]
[/quote]
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.