Jump to content

[SOLVED] Upload Image & Post MYSQL Info - Help


methosk

Recommended Posts

Ok, so what I am attempting is to upload an image, and have the name of the image saved into a MYSQL Db, however with my current code I am doing neither for some reason :/

 

<form enctype="multipart/form-data" action="upload2.php" method="POST">
Please choose a file for Image 2: <input name="uploaded" type="file" /><br />
<input id="add2" name="add2" type="submit" value="Upload" />
</form> 

<?php

//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 = "images/";
//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 "The file has been uploaded";
} 
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>
<?php
mysql_connect("localhost", "XXXX", "XXX") or
    die("Could not connect: " . mysql_error());
if(isset($_POST['add2']))
{
$id = "1";
$img = $ran2.$ext;
mysql_select_db("XXX");
$query = "INSERT INTO slidshow (id, img) VALUES ('$id', '$img')";
mysql_query($query) or die('Error, insert query failed');
$query = "FLUSH PRIVILEGES";
mysql_query($query) or die('Entry Added');}
else
{
}
?>

 

I couldn't find a way to separate the name of the file, all I could find was how to separate the extension so that you could change the filename :/

 

So what I settled for was to just change the name to a random number, and then upload that number to my MYSQL DB. However, atm it's not doing either :/ If anyone could help me with this code (or think of a code where I can just copy the uploaded filename to my DB without actually changing the filename) I would be very thankful for your help :)

 

Ok, that code is a lot better, agreed. I am currently using that, and it does in fact upload the files lol. However, I still can't manage to add a Mysql Insert Query, because I keep getting "Error, insert query failed". I am assuming its because of my lack of ability when it comes to coding, so I will just put the code here-

 

<?php


mysql_connect("localhost", "xxxx", "xxxx") or
    die("Could not connect: " . mysql_error());

// filename: upload.processor.php

// first let's set some variables

// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);

// make a note of the directory that will recieve the uploaded file
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';

// make a note of the location of the upload form in case we need it
$uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.form.php';

// make a note of the location of the success page
$uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.success.php';

// fieldname used within the file <input> of the HTML form
$fieldname = 'file';

// Now let's deal with the upload

// possible PHP upload errors
$errors = array(1 => 'php.ini max file size exceeded',
                2 => 'html form max file size exceeded',
                3 => 'file upload was only partial',
                4 => 'no file was attached');

// check the upload form was actually submitted else print the form
isset($_POST['submit'])
    or error('the upload form is neaded', $uploadForm);

// check for PHP's built-in uploading errors
($_FILES[$fieldname]['error'] == 0)
    or error($errors[$_FILES[$fieldname]['error']], $uploadForm);
    
// check that the file we are working on really was the subject of an HTTP upload
@is_uploaded_file($_FILES[$fieldname]['tmp_name'])
    or error('not an HTTP upload', $uploadForm);
    
// validation... since this is an image upload script we should run a check  
// to make sure the uploaded file is in fact an image. Here is a simple check:
// getimagesize() returns false if the file tested is not an image.
@getimagesize($_FILES[$fieldname]['tmp_name'])
    or error('only image uploads are allowed', $uploadForm);
    
// make a unique filename for the uploaded file and check it is not already
// taken... if it is already taken keep trying until we find a vacant one
// sample filename: 1140732936-filename.jpg
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
    $now++;
}


// now let's move the file to its final location and allocate the new filename to it
@move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
    or error('receiving directory insuffiecient permission', $uploadForm);

// MySQL Insert Query
$id = "1";
$img = $fieldename;
mysql_select_db("XXXX");
$query = "INSERT INTO slidshow (id, img) VALUES ('$id', '$img')";
mysql_query($query) or die('Error, insert query failed');
$query = "FLUSH PRIVILEGES";
mysql_query($query) or die('Entry Added');



// If you got this far, everything has worked and the file has been successfully saved.
// We are now going to redirect the client to a success page.
header('Location: ' . $uploadSuccess);

// The following function is an error handler which is used
// to output an HTML error page if the file upload fails
function error($error, $location, $seconds = 5)
{
    header("Refresh: $seconds; URL=\"$location\"");
    echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
    '"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
    '<html lang="en">'."\n".
    '    <head>'."\n".
    '        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n".
    '        <link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
    '    <title>Upload error</title>'."\n\n".
    '    </head>'."\n\n".
    '    <body>'."\n\n".
    '    <div id="Upload">'."\n\n".
    '        <h1>Upload failure</h1>'."\n\n".
    '        <p>An error has occured: '."\n\n".
    '        <span class="red">' . $error . '...</span>'."\n\n".
    '         The upload form is reloading</p>'."\n\n".
    '     </div>'."\n\n".
    '</html>';
    exit;
} // end error handler

?> 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.