[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

Uploading Images through a forn

Posted on 2010-04-09
9
Medium Priority
?
186 Views
Last Modified: 2013-12-13
Hi, I would be very grateful if you could please help me to solve the problem I have with uploading images through DB.

The idea is for user to enter specific info and also upload an image. The results the user e enters must then be displayed on a separate php page.

Here is what I tried so far (the form works except that the image is not saving to DB. I don't know how coding should be implementing here. Thank you in advance!
CREATE TABLE IF NOT EXISTS `form` (
  `id` int(11) NOT NULL auto_increment,
  `name` char(60) NOT NULL default '',
  `surname` char(60) NOT NULL default '',
  `email` char(100) NOT NULL default '',
  `comment` char(255) NOT NULL default '',
  `image` varchar(30) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

form.php
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php");  ?>


<?php find_selected_page(); ?>
<?php include("includes/header.php");

if(!isset($_SESSION['name'])) $_SESSION['name'] = '';
if(!isset($_SESSION['surname'])) $_SESSION['surname'] = '';
if(!isset($_SESSION['email'])) $_SESSION['email'] = '';
if(!isset($_SESSION['comment'])) $_SESSION['comment'] = '';
if(!isset($_SESSION['image'])) $_SESSION['image'] = '';

echo '<table width="310" border="0" cellpadding="0" cellspacing="0">
<form name="form" action="validation.php" method="post">
  <tr>
    <td height="36" colspan="3" valign="top"><h2>form</h2><br><br>
    Your comment must be at least 255 characters.</td>
    <td width="1"></td>
  </tr>
  <tr>
    <td width="80" height="19" valign="top">&nbsp;</td>
    <td width="15" rowspan="10" valign="top">&nbsp;</td>
    <td width="214" valign="top">&nbsp;</td>
    <td></td>
  </tr>
  <tr>
    <td height="22" align="left" valign="top">Name:</td>
    <td valign="top">
      <input type="text" name="name" value="'.$_SESSION['name'].'">    </td>
    <td></td>
  </tr>
  <tr>
    <td height="7"></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td height="22" align="left" valign="top">Surname:</td>
    <td valign="top"><input type="text" name="surname" value="'.$_SESSION['surname'].'"></td>
    <td></td>
  </tr>
  <tr>
    <td height="9"></td>
    <td></td>
    <td></td>
  </tr>
   <tr>
    <td height="10"></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td height="22" align="left" valign="top">Email:</td>
    <td valign="top"><input type="text" name="email" value="'.$_SESSION['email'].'"></td>
  
  </tr>
  <tr>
    <td height="9"></td>
     
  </tr>
  <tr>
    <td height="19" align="left" valign="top">Comment:</td>
    <td rowspan="2" valign="top"><textarea name="comment" cols="30" rows="5" value="'.$_SESSION['comment'].'">'.$_SESSION['comment'].'</textarea></td>
   
  </tr>
  <tr>
    <td colspan="2" rowspan="3" valign="top">&nbsp;</td>
    <td height="83"></td>
  </tr>
  <tr>
    <td height="17" valign="top">&nbsp;</td>
   
  </tr>
 
 
 
 
<?php

// In an application, this could be moved to a config file
$upload_errors = array(
	// http://www.php.net/manual/en/features.file-upload.errors.php
	UPLOAD_ERR_OK 				=> "No errors.",
	UPLOAD_ERR_INI_SIZE  	=> "Larger than upload_max_filesize.",
  UPLOAD_ERR_FORM_SIZE 	=> "Larger than form MAX_FILE_SIZE.",
  UPLOAD_ERR_PARTIAL 		=> "Partial upload.",
  UPLOAD_ERR_NO_FILE 		=> "No file.",
  UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
  UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
  UPLOAD_ERR_EXTENSION 	=> "File upload stopped by extension."
);

if(isset($_POST['submit'])) {
	// process the form data
	$tmp_file = $_FILES['file_upload']['tmp_name'];
	$target_file = basename($_FILES['file_upload']['name']);
	$upload_dir = "uploads";
  
	// You will probably want to first use file_exists() to make sure
	// there isn't already a file by the same name.
	
	// move_uploaded_file will return false if $tmp_file is not a valid upload file 
	// or if it cannot be moved for any other reason
	if(move_uploaded_file($tmp_file, $upload_dir."/".$target_file)) {
		$message = "File uploaded successfully.";
	} else {
		$error = $_FILES['file_upload']['error'];
		$message = $upload_errors[$error];
	}
	
}	

?>
<html>
	<head>
		<title>Upload</title>
	</head>
	<body>
	
<?php
// The maximum file size (in bytes) must be declared before the file input field
// and can't be larger than the setting for upload_max_filesize in php.ini.
//
// This form value can be manipulated. You should still use it, but you rely 
// on upload_max_filesize as the absolute limit.
//
// Think of it as a polite declaration: "Hey PHP, here comes a file less than X..."
// PHP will stop and complain once X is exceeded.
// 
// 1 megabyte is actually 1,048,576 bytes.
// You can round it unless the precision matters.
?>

		<?php if(!empty($message)) { echo "<p>{$message}</p>"; } ?>
		<form action="upload.php" enctype="multipart/form-data" method="POST">

		  <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
		  <input type="file" name="file_upload" />

		  <input type="submit" name="submit" value="Upload" />
		</form>
	
	</body>
</html>  
  
  
  
  
  
  
  
  
  
  
  
  
  
    
  <tr>
    <td height="24" valign="top"><input name="Send" type="submit" id="Send" value="Send">
      <input name="Reset" type="reset" id="Reset" value="Reset"> </td>
   
  </tr>
  </form>
</table>';




processing.php
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php");  ?>


<?php find_selected_page(); ?>
<?php include("includes/header.php");


if(($_SESSION['name'] == "") || ($_SESSION['surname'] == "") || ($_SESSION['email'] == "") || ($_SESSION['comment'] == "") || (strlen($_SESSION['comment']) > 255) || ($_SESSION['image'] == "") )




{
echo 'You have not enetered all the information in the form or the ones you have entered are not valid. <br>
      Click <a href="form.php">here</a> to go to previous page.';
}
else
{
echo 'Thank you.<br>
      The information was sucesfully added into the system. <br>
      To view your comment click <a href="view.php">here</a>.';
   
$requestSQL = "INSERT INTO `form` (`name`, `surname`, `email`, `comment`, 'image')
              VALUES ('".$_SESSION['name']."', '".$_SESSION['surname']."', '".$_SESSION['email']."', '".$_SESSION['comment']."', '".$_SESSION['image']."');";
			  
			  
			  
mysql_query($requestSQL);

$_SESSION['name'] = '';
$_SESSION['surname'] = '';
$_SESSION['email'] = '';
$_SESSION['comment'] = '';
$_SESSION[['image'] = '';

}
 echo "<br>", "<br>", "<br>", "<br>", "<br>","<br>", "<br>";
?>


validation.php

<?php require_once("includes/session.php"); ?>
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php");  ?>


<?php find_selected_page(); ?>
<?php include("includes/header.php");


$_SESSION['name'] = addentities($_POST['name']);
$_SESSION['surname'] = addentities($_POST['surname']);
$_SESSION['email'] = addentities($_POST['email']);
$_SESSION['comment'] = addentities($_POST['comment']);
$_SESSION['image'] = addentities($_POST['image']);

echo 'Name: '.$_SESSION['name'].'<br>
      Surname: '.$_SESSION['surname'].'<br>
	   Email: '.$_SESSION['email'].'<br>
	  Comment: '.$_SESSION['comment'].'<br>
	  Image: '.$_SESSION['image'].'<br>
	   
	  If the information enetered is correct, click <a href="processing.php">here</a> to validate <br>
	  and to add it into the system.';

?>

view.php

<?php require_once("includes/session.php"); ?>
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php");  ?>


<?php find_selected_page(); ?>
<?php include("includes/header.php");
					

   $requestSQL = 'SELECT * FROM `form`'; 
   $result = mysql_query($requestSQL);
   while($line = mysql_fetch_array($result))
   {
    echo '<b>Name:</b> '.$line['name'].' <br>
	      <b>Surname:</b> '.$line['surname'].' <br>
		   <b>Email:</b> '.$line['email'].' <br>
		  <b>Comment:</b> '.$line['comment'].' <br>
		  
		  <b>Image:</b> '.$line['image'].' <br>' ;
	  
		  
   }   

?>

Open in new window

0
Comment
Question by:rely7
  • 3
  • 3
7 Comments
 
LVL 6

Expert Comment

by:Ludwig Diehl
ID: 30221030
You can try this. Note that I am only saving the image location onto the DB and displaying the content of the table so you know you have loaded it successfully.
<?php 
if(is_uploaded_file($_FILES['file_upload']['tmp_name']))
    if(move_uploaded_file($_FILES['file_upload']['tmp_name'],dirname(__FILE__).'/'.$_FILES['file_upload']['name']))
    {
        $image  = $_FILES['file_upload']['name'];
        $query  = "INSERT INTO form(image) VALUES('$image')";
        $cn     = mysql_connect('server','user','pwd');
        mysql_select_db('db');
        if(mysql_query($query,$cn))
            echo "Image saved!";
        $query  = "SELECT * FROM form";       
        $rs     = mysql_query($query,$cn);
    }
?>
<html>
    <head>
    </head>
    <body>
        <form action="" enctype="multipart/form-data" method="POST">        
            <input type="hidden" name="MAX_FILE_SIZE" value="10000000000000000" />
            <input type="file" name="file_upload" />        
            <input type="submit" name="submit" value="Upload" />

        </form>
        <?php
        while($result=mysql_fetch_assoc($rs))
            {
                $uploadedFile=$result['image'];
                echo "<img src=\"$uploadedFile\"/>";
            }        
            
        ?>
    </body>
</html>

Open in new window

0
 

Author Comment

by:rely7
ID: 30224267
Thanks a lot for your fast response. I have some errors and I don't know how to solve them.

In your code you have called connection but I've also included it on the top. I can't understand why.

Sorry, do you mind if you post me exactly where I should place that code into the form and if I have to add something else? Sorry I'm just trying to learn php and hope you understand me. Thank you.
0
 

Author Comment

by:rely7
ID: 30387560
Sory could you please tell me exactly where should Iplace this code in the form as it doesn't seem to work? Thanks a lot.
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 6

Accepted Solution

by:
Ludwig Diehl earned 1000 total points
ID: 30525351
well, I put it coz I embedded the connection process. First you have to separate the form file from the processing page.

1.form.php (note that u may want to change the size limit..)

<html>
    <head>
    </head>
    <body>
        <form action="processing.php" enctype="multipart/form-data" method="POST">        
            <input type="hidden" name="MAX_FILE_SIZE" value="10000000000000000" />
            <input type="file" name="file_upload" />        
            <input type="submit" name="submit" value="Upload" />

        </form>
        <?php
        while($result=mysql_fetch_assoc($rs))
            {
                $uploadedFile=$result['image'];
                echo "<img src=\"$uploadedFile\"/>";
            }        
           
        ?>
    </body>
</html>


2. processing.php

<?php
require_once('connections.php');
if(is_uploaded_file($_FILES['file_upload']['tmp_name']))
    if(move_uploaded_file($_FILES['file_upload']['tmp_name'],dirname(__FILE__).'/'.$_FILES['file_upload']['name']))
    {
        $image  = $_FILES['file_upload']['name'];
        $query  = "INSERT INTO form(image) VALUES('$image')";
        if(mysql_query($query,$cn))
            echo "Image saved!";
        $query  = "SELECT * FROM form";      
        $rs     = mysql_query($query,$cn);
        if($rs)
            echo "OK!";
    }
?>

By the way the images added should be automatically displayed? or only if user wants to?.





0
 

Author Comment

by:rely7
ID: 30549005
Thank you so much for your time...I added the code to mine but still gives me error with string. I added the code you gave me, at the end, is it right?  The error is "Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' i "   I can't see anything wrong with the syntax.

The images added I want to be displayed automatically together with the users input personal details.

I would really appreciate if you llok into this a bit more if you can please. Thanks a lot!

0
 
LVL 6

Expert Comment

by:Ludwig Diehl
ID: 30773587
try this sorry for the delay
project.zip
0
 
LVL 8

Expert Comment

by:Tocacar
ID: 39674034
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0

Featured Post

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this. Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it i…
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

591 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question