Solved

Problem with PHP Script Inserting Image name into database

Posted on 2010-09-01
17
239 Views
Last Modified: 2012-05-10
Hi Experts,

I have  form that is mostly working. You can see it in action here:

http://www.enviromedia.com/careers/xm-recruiting/

If I complete the form but DO NOT upload an image, it inserts into the database.

If I complete the form AND insert an image, the image correctly uploads, but the record does not write to the database. I have successfully used this form on another server, and it seemed to be working yesterday.

I've attached the code for your review.

Thanks for any and all suggestions!

Lisa

<?php
/**
 * @package WordPress
 * @subpackage Default_Theme
 * Template Name: XM Recruiting */

get_header(); 

/*include_once '/var/configuration/configuration.php'; */

?>

	<?php if (have_posts()) : ?>

		<?php while (have_posts()) : the_post(); ?>

			<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
            
            <div class="grid_18_sub left_0">
				<div class="grid_9">
				<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>" class="green"><?php the_title(); ?></a></h2>
<?php

include(TEMPLATEPATH.'/recaptchalib.php');
$privatekey = "6LfNXQEAAAAAAHqCuBViPNfRYvytsmSg-U7nSLrH";
?>

 <script type="text/javascript">
 var RecaptchaOptions = {
    theme : 'clean'
 };
 </script>
<?php 

if(isset($_POST['op'])) {
	
		// connect and select:
	$dbc = mysql_connect('xxxx', 'xxxx', 'xxxxxx');
	mysql_select_db('xxxxxx');

	error_reporting(E_ALL | E_STRICT);
	
	$resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);
                                
$recaptcha_error = "0";
if (!$resp->is_valid) {
  $recaptcha_error = "1";
}//close if for recaptcha error 1 



if ($recaptcha_error != 1) {
		
	$recruit_id = $_POST['id'];
  	$date_entered = $_POST['date_entered'];
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $sun = $_POST['sun'];
    $mon = $_POST['mon'];
    $tues = $_POST['tues'];
    $wed = $_POST['wed'];
    $thur = $_POST['thur'];
    $fri = $_POST['fri'];
    $sat = $_POST['sat'];
    $notice = $_POST['notice'];
    $spanish = $_POST['spanish'];
    $overnight = $_POST['overnight'];
    $large_vehicles = $_POST['large_vehicles'];
	$photo = $_POST['photo'];
	
//Validate the form data:
	$problem = FALSE;
	
	if (!empty($_POST['first_name']) ) {
		$first_name = mysql_real_escape_string(trim($_POST['first_name']));
	} else {
		echo "<p>Please enter your first name.</p><p><a href='javascript: history.go(-1)'>Click here to go back</a>.</p>";
		$problem = TRUE;
	}
	
	if (!empty($_POST['last_name']) ) {
		$last_name = mysql_real_escape_string(trim($_POST['last_name']));
	} else {
		echo "<p>Please enter your last name.</p><p><a href='javascript: history.go(-1)'>Click here to go back</a>.</p>";
		$problem = TRUE;
	}
	
	if (!empty($_POST['phone']) ) {
		$phone = mysql_real_escape_string(trim($_POST['phone']));
	} else {
		echo "<p>Please enter your phone number.</p><p><a href='javascript: history.go(-1)'>Click here to go back</a>.</p>";
		$problem = TRUE;
         }

        if (!empty($_POST['email']) ) {
		$email = mysql_real_escape_string(trim($_POST['email']));
	} else {
		echo "<p>Please enter your e-mail address.</p><p><a href='javascript: history.go(-1)'>Click here to go back</a>.</p>";
		$problem = TRUE;
	}
	
	 
	//Validate photo 
	
    // Declare variables
    // Get the basic file information
    $userfile = $_FILES['photo']['name'];
    $file_size = $_FILES['photo']['size'];
    $file_temp = $_FILES['photo']['tmp_name'];
    $file_err = $_FILES['photo']['error'];
    $path = '/var/www/html/xm-uploads/';

    // Create a new file name
    // This is so if other files on the server have the same name, it will be renamed
    $randomizer = rand(0000, 9999);
    $file_name = $randomizer.$userfile;
    
   if(!empty($userfile)) {
        
        // limit the size of the file to 200KB
        if($file_size > 1000000) {
            echo 'Your photo is too large to upload. Please reduce the filesize to less than 200KB.';
            exit();
        }
		
		//sniff file mime type to make sure it is really an image
		
        
		
		function  image_valid($type)
		{
		$file_types  = array(
			'image/jpeg'     => 'jpg',
			'image/pjpeg'    => 'jpg',  
			'image/jpeg'     => 'jpg',
			'image/jpeg'     => 'jpeg',
  			);
	
		if(array_key_exists($type, $file_types))
			{		
			return true;
			}
			else
			{
			echo 'Your photo is the wrong format. Please change the photo format to .JPG or .JPEG.';
			}
		}
  
		
		if(move_uploaded_file($file_temp, '/var/www/html/xm-uploads/' .$file_name.'')) {
			 
            //echo '<p>File upload successful.</p>';
			//echo "value passed to move-uploaded-file ---" .  '/var/www/html/xm-uploads/' .$file_name;
        } else {
			//echo "value passed to move-uploaded-file ---" .  '/var/www/html/xm-uploads/' .$file_name;
            echo '<p>Your photo file has not been uploaded due to an error. Error number ' . $file_err . '</p>';
            //echo "value passed to move-uploaded-file ---" .  '/var/www/html/xm-uploads/' .$file_name;
             }
        
//        echo "IMAGE FILE NAME --- ".$file_name;
		$image = new SimpleImage();
   		$image->load($path.$file_name);
   		$image->resizeToWidth(350);
   		$image->save($path.$file_name);
   		
   		//print $image . "there is where I print the image name <br />.";
   		
   	    } // close not empty if statement 
   
		
	
    if (!$problem) {//there is no problem so insert into database
	
		// Define the query:
		$query = "INSERT INTO applicants (id_recruit, date_entered, revised_date, first_name, last_name, phone, email, sun, mon, tues, wed, thur, fri, sat, notice, spanish, overnight, large_vehicles, photo) VALUES ('', '$date_entered', NOW(), '$first_name', '$last_name', '$phone', '$email', '$sun', '$mon', '$tues', '$wed', '$thur', '$fri', '$sat', '$notice', '$spanish', '$overnight', '$large_vehicles', '$file_name')";
		
		// execute the query

		if (@mysql_query($query)) {
			print'<p class="error">Your entry form has been added.</p>';
			} else {
			print '<p class="error">could not add the entry because:<br />' . mysql_error() . '.</p><p>the query being run was: ' . $query . '</p>';
		}
		
	}//no problem
	
} //close if recaptcha error !1

if ($recaptcha_error == "1") {
	echo "<p>There was an error in your response to the captcha (image with distorted letters).</p><p><a href='javascript: history.go(-1)'>Click here to go back</a>.</p>";
}
	
	mysql_close();
	
     }  else { // end form submission if -- display the form

	 
	 ?>
     <div class="entry">
					<?php the_content('Read the rest of this entry &raquo;'); ?>
				</div>
				
				   <form method="post" name="http://www.enviromedia.com/careers/xm-recruiting/" enctype="multipart/form-data">
     
        <p><label for="date_entered">Date:</label>
        <br /><input name="date_entered" type="text" id="date_entered" size="10" value="<?php echo stripslashes($date_entered); ?>">
        <br />(01/01/2010)
        </p>
        
        <p><span class="required"><strong><label for="first_name">*First Name:</label> </strong></span>
        <br /><input name="first_name" type="text" id="first_name" size="50" value="<?php echo stripslashes($first_name); ?>">
        </p>
        
        <p><span class="required"><strong><label for="last_name">*Last Name:</label> </strong></span>
        <br /><input name="last_name" type="text" id="last_name" size="50" value="<?php echo stripslashes($last_name); ?>">
        </p>

        <p><label for="phone"><strong>*Contact Number:</strong></label>
        <br /><input name="phone" type="text" id="phone" size="50" value="<?php echo stripslashes($phone); ?>">
        <br />XXX-XXX-XXXX
        </p>
        
          <p>
          <span class="required"><strong><label for="email">*E-mail:</label></strong></span>
          <br /><input name="email" type="text" id="email" size="50" value="<?php echo stripslashes($email); ?>">
</p>
       
	      <table cellpadding="4" cellspacing="0" border="0">
          <tr><td colspan="2">Availability:</td></tr>
          
          <tr><td><label for="sunday">Sunday: </label></td><td><input name="sun" type="checkbox" id="sun" value="Yes"></td></tr>
          <tr><td><label for="monday">Monday: </label></td><td><input name="mon" type="checkbox" id="mon" value="Yes"></td></tr>
          <tr><td><label for="tuesday">Tuesday: </label></td><td><input name="tues" type="checkbox" id="tues" value="Yes"></td></tr>
          <tr><td><label for="wednesday">Wednesday: </label></td><td><input name="wed" type="checkbox" id="wed" value="Yes"></td></tr>
          <tr><td><label for="thursday">Thursday: </label></td><td><input name="thur" type="checkbox" id="thur" value="Yes"></td></tr>
          <tr><td><label for="friday">Friday: </label></td><td><input name="fri" type="checkbox" id="fri" value="Yes"></td></tr>
          <tr><td><label for="saturday">Sunday: </label></td><td><input name="sat" type="checkbox" id="sat" value="Yes"></td></tr>
          </table>
          
          <p>
          <label for="email">How much notice do you need to work?:</label>
          <br /><input name="notice" type="text" id="notice" size="75" value="<?php echo stripslashes($notice); ?>">
</p>
         
         <table cellpadding="4" cellspacing="0" border="0">
          
          
          <tr><td><label for="spanish">Spanish/English Bilingual? </label></td><td><input name="spanish" type="checkbox" id="spanish" value="Yes"></td></tr>
          <tr><td><label for="overnight">Are you able to travel orvernight?: </label></td><td><input name="overnight" type="checkbox" id="overnight" value="Yes"></td></tr>
          <tr><td><label for="large_vehicles">Can you drive large vehicles (i.e. trucks, rv, etc.)? </label></td><td><input name="large_vehicles" type="checkbox" id="large_vehicles" value="Yes"></td></tr>
         
          </table>
         <label for="photo"><br />
           Optional: Upload a photo of your bad habit and/or solution (<!--Should be -->JPEG or JPG format<!-- with dimensions of 200 x 300 pixels-->)</label><br />
			<input name="photo" type="file" value="<?php echo stripslashes($_POST['photo']); ?>" id="photo" />
			<br />
			<br />
			<?php
//print "something should show up here, too";
$publickey = "6LfNXQEAAAAAAHPo1aKlAVhLL-7nNuLxQRs2xRa-"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
      
<p> 
          <input name="Submit" type="submit" value="Submit">
          <input type="reset" name="Submit2" value="Reset">
          <br>
        </p>
		<input type="hidden" name="email_subject" value="Submit" />
                <input type="hidden" name="op" value="true" />
		   		
          <br>
       
             </form>
          		
<?php
}//close else not success
?>
</div><!-- end grid 9 -->
</div><!-- end grid 18 -->

<!-- begin sidebar here --><div class="grid_4_sub"><h2 class="green">Current Openings</h2>

<div id="sidebar">

<?php include 'sub_careers_sidebar.php';?>

</div>
</div>
<!--end grid 4 sidebar-->
<div class="clear"></div>
			
			</div>

		<?php endwhile; ?>

	<?php else : ?>


	<?php endif; ?>


<?php get_footer(); ?>

Open in new window

0
Comment
Question by:lisacowan
  • 7
  • 5
  • 4
  • +1
17 Comments
 
LVL 2

Expert Comment

by:Tiller79188231
ID: 33581279
what is the field type of photo? also what is a sample of the data trying to be inserted?... maybe post a complete sql statement with sample data?
0
 

Author Comment

by:lisacowan
ID: 33581839
Thanks for the comment.

The photo is a jpg. I'm uploading it to a directory, renaming it and putting the name in the database.The photo itself is never written to the database.

The rest of the data is text. If you submit the form without trying to submit a photo, you will see the INSERT statement. This is the one I just got.

INSERT INTO applicants (id_recruit, date_entered, revised_date, first_name, last_name, phone, email, sun, mon, tues, wed, thur, fri, sat, notice, spanish, overnight, large_vehicles, photo) VALUES ('', '07/10/2010', NOW(), 'Lisa', 'Cowan', '512-468-4200', 'cowan_lisa@att.net', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'none', 'Yes', 'Yes', 'Yes', '7800')

Note that there is a file name for the photo when there shouldn't be a value there.

Does this help?

Lisa
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 33584878
what is the column type in the database for the image ? varchar ?
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 33584900
When you select an image, the file is uploaded to server but the query does not work or the query inserts empty string in the place of 'photo' ?
0
 

Author Comment

by:lisacowan
ID: 33585191
The column type for the photo is VARCHAR because only the name gets inserted into the database.

When I select an image the file does get uploaded but the query does not work at all. No record is inserted into the database.

Thanks for the comments,
Lisa
0
 
LVL 5

Expert Comment

by:onemadeye
ID: 33585193
How about this...

On your codes ( line 121 as above ) :
$file_name = $randomizer.$userfile;

Change it to:
$file_name = isset($userfile) ? $randomizer.$userfile : '';

So, $file_name should be set to nothing if there is no image uploaded.

Let me know ...
0
 

Author Comment

by:lisacowan
ID: 33585225
Thanks, onemadeye. I'll try it when I get into the office.

Lisa
0
 
LVL 2

Expert Comment

by:Tiller79188231
ID: 33586053
That will take care of inserting something random if there is no image uploaded.. but what about when an image IS uploaded? You never posted the resulting sql statement, or said if the query tried to execute at all or not
0
 

Author Comment

by:lisacowan
ID: 33586389
@onemadeye,

Thanks for the comment. I changed line 121 of the code, but it is still inserting a number into the photo column if there is no picture uploaded. Do you have any other suggestions?

Thanks again,
Lisa
0
 

Author Comment

by:lisacowan
ID: 33586435
@Tiller79188231:

I'm a little confused. Is this the code you want to see?

INSERT INTO applicants (id_recruit, date_entered, revised_date, first_name, last_name, phone, email, sun, mon, tues, wed, thur, fri, sat, notice, spanish, overnight, large_vehicles, photo) VALUES ('', '$date_entered', NOW(), '$first_name', '$last_name', '$phone', '$email', '$sun', '$mon', '$tues', '$wed', '$thur', '$fri', '$sat', '$notice', '$spanish', '$overnight', '$large_vehicles', '$file_name')

The query statement does not execute if I try to upload an image. Nothing is inserted into the database.

Thanks for the help,
Lisa
0
 
LVL 2

Expert Comment

by:Tiller79188231
ID: 33586459
The sql statement that is generated when you try to submit with uploading an image... the complete statement with the values in place of the variables
0
 

Author Comment

by:lisacowan
ID: 33586650
@Tiller79188231:

The SQL won't print if I try to insert an image. It looks to me like the script just stops executing in the middle of the move_uploaded_file if statement. The file uploads, but does not resize.

The more I look at the script, I can't figure out how it worked in the first place.

Thanks for the help.

Lisa
0
 
LVL 2

Accepted Solution

by:
Tiller79188231 earned 500 total points
ID: 33586868
$image = new SimpleImage();

your not including the php class that has the SimpleImage() function.
Also, you have error reporting set to strict, so you should have gotten an error saying reference to function was invalid or missing
0
 

Author Closing Comment

by:lisacowan
ID: 33587063
That did the trick. Thank you very much.
0
 
LVL 2

Expert Comment

by:Tiller79188231
ID: 33587163
Your welcome!
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 33589967
what happens if you uncomment these echo lines, what's the output ?
if(move_uploaded_file($file_temp, '/var/www/html/xm-uploads/' .$file_name.'')) {
			 
echo '<p>File upload successful.</p>';
echo "value passed to move-uploaded-file ---" .  '/var/www/html/xm-uploads/' .$file_name;
        } else {
echo "value passed to move-uploaded-file ---" .  '/var/www/html/xm-uploads/' .$file_name;
            echo '<p>Your photo file has not been uploaded due to an error. Error number ' . $file_err . '</p>';
echo "value passed to move-uploaded-file ---" .  '/var/www/html/xm-uploads/' .$file_name;
             }

Open in new window

0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 33589978
finished. lol
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Finding original email is quite difficult due to their duplicates. From this article, you will come to know why multiple duplicates of same emails appear and how to delete duplicate emails from Outlook securely and instantly while vital emails remai…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…

813 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now