Data not going into Database

PHP - MySQL

I am attempting to create a page that uploads images and saves them for viewing for members who belong to a website.

The page is posting to itself but not putting anything into the database, not letting the viewer know it has been uploaded OR giving any kind of error message. I took out one of the fields – description – as it is not needed so I am wondering if there is anything in the code that still refers to this field and the rest of the data is just not going into the database to begin with. My database columns are – file_name, file_size, file_type.

<?php 

require ('./includes/config.inc.php');

require (MYSQL);

$counter = 3; // Number of files to allow for.

if (isset($_POST['submitted'])) { // Handle the form.

	//require_once ('mysql_connect.php'); // Connect to the database.
	
	for ($i = 0; $i < $counter; $i++) { // Handle each uploaded file.
	
		// Create index names to refer to the proper upload and description.
		$filename = 'upload';
	
		// Check for a file.
		if (isset($_FILES[$filename]) && ($_FILES[$filename]['error'] != 4)) {

			
			// Add the record to the database.
			$query = "INSERT INTO notices (file_name, file_size, file_type) VALUES ('{$_FILES[$filename]['name']}', {$_FILES[$filename]['size']}, '{$_FILES[$filename]['type']}')";
			$result = mysql_query ($query);
		
			if ($result) {
				
				// Return the upload_id from the database.
				$upload_id = mysql_insert_id();
				
				// Move the file over.
				if (move_uploaded_file($_FILES[$filename]['tmp_name'], "./YEuploads/$upload_id")) {
				
					echo '<p>File number ' . ($i + 1) . ' has been uploaded!</p>';
					
				} else { // File could not be moved.
				
					echo '<p><font color="red">File number ' . ($i + 1) . ' could not be moved.</font></p>';
		
					// Remove the record from the database.
					$query = "DELETE FROM uploads WHERE upload_id = $upload_id";
					$result = mysql_query ($query);
				
					}
				
			} else { // If the query did not run OK.
				echo '<p><font color="red">Your submission could not be processed due to a system error. We apologize for any inconvenience.</font></p>'; 
				// Print the query and invoke the mysql_error() function to debug.
			}
			
		} // End of if (isset($the_file)...
		
	} // End of FOR loop.
	
	mysql_close(); // Close the database connection.
		
} // End of the main Submit conditional.
?>
<form enctype="multipart/form-data" action="add_file.php" method="post">

	<fieldset><legend>Fill out the form to upload a file:</legend>
	<input type="hidden" name="MAX_FILE_SIZE" value="524288">
	
	<?php // Create the inputs.
	for ($i = 0; $i < $counter; $i++) {
		echo '<p><b>File:</b> <input type="file" name="upload' . $i . '" /></p>';
	}
	?>
	
	</fieldset>
	<input type="hidden" name="submitted" value="TRUE" />
	<div align="center"><input type="submit" name="submit" value="Submit" /></div>

</form>

Open in new window

Wanda MarstonCreative DirectorAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
OK. First of all, I would suggest you turn on error_reporting and then run your script again. Right at the start of your script, add these 2 lines:

error_reporting(E_ALL);
ini_set('display_errors', 1);

Open in new window

Now you will see any errors in your script output to the screen.

Next, you are using the old mysql functions. These are now deprecated and shouldn't be used. If you're using php 7, then they've been removed altogether. You should at the very least be using mysqli (notice the i at the end)

Run your script with error reporting turned on and report back
0
Wanda MarstonCreative DirectorAuthor Commented:
I understand what you have said above. I added the two lines.

I did not get any kind of error and the page is still acting the same. I have other pages in the website that are using the older codin and for the time being, working.
0
Chris StanyonWebDevCommented:
Something else I've just noticed - your file inputs are called upload0, upload1 and upload2, but in your script you're doing an isset on $_FILES['upload']. This will always return false, so your entire processing block will be skipped.

You will need to tag the loop number onto the input name:

$filename = 'upload' . $i;
0
Newly released Acronis True Image 2019

In announcing the release of the 15th Anniversary Edition of Acronis True Image 2019, the company revealed that its artificial intelligence-based anti-ransomware technology – stopped more than 200,000 ransomware attacks on 150,000 customers last year.

Wanda MarstonCreative DirectorAuthor Commented:
Okay I changed that line and now I get this error message three times which is telling me that the three file id's could not be moved to the YEimages file?

Your submission could not be processed due to a system error. We apologize for any inconvenience.

Your submission could not be processed due to a system error. We apologize for any inconvenience.

Your submission could not be processed due to a system error. We apologize for any inconvenience.

This is where my file seems to be stuck even before I removed the "description" field in the form.
0
Chris StanyonWebDevCommented:
The error has nothing to do with moving the file - your code doesn't even get to the move_uploaded_file() part. The error is being generated because your query failed to insert into the database.

Change the query code to this:

$name = $_FILES[$filename]['name'];
$size = $_FILES[$filename]['size'];
$type = $_FILES[$filename]['type'];

$query = "INSERT INTO notices (file_name, file_size, file_type) VALUES ('$name', '$size', '$type')";
$result = mysql_query ($query);

Open in new window

And then add an error report in the else block

} else { // If the query did not run OK.
    echo '<p><font color="red">Your submission could not be processed due to a system error. We apologize for any inconvenience.</font></p>'; 
    echo mysql_errno() . ": " . mysql_error();
}

Open in new window

Overall, I would strongly suggest you recode your entire script. It hugely outdated -  the mysql functions are deprecated, the <font> tag is deprecated. Your file inputs should be passed as an array, and you should be running the query in a transaction, with a commit and rollback mechanism instead of the insert / delete that you currently have. It'll make your code much more reliable
0
Wanda MarstonCreative DirectorAuthor Commented:
Thanks. Appreciate your reply.

changed the above code and the page reacts the same as before. It posts to itself but I do not get a statement saying that the files have been uploaded or and error message.
0
Chris StanyonWebDevCommented:
OK. Post up your full code as you now have it.
0
Wanda MarstonCreative DirectorAuthor Commented:
<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);


require ('./includes/config.inc.php');

require (MYSQL);

$counter = 3; // Number of files to allow for.

if (isset($_POST['submitted'])) { // Handle the form.

	//require_once ('mysql_connect.php'); // Connect to the database.
	
	for ($i = 0; $i < $counter; $i++) { // Handle each uploaded file.
	
		// Create index names to refer to the proper upload and description.
		$filename = 'upload' . $i; ;
	
		// Check for a file.
		if (isset($_FILES[$filename]) && ($_FILES[$filename]['error'] != 4)) {

$name = $_FILES[$filename]['name'];
$size = $_FILES[$filename]['size'];
$type = $_FILES[$filename]['type'];

$query = "INSERT INTO notices (file_name, file_size, file_type) VALUES ('$name', '$size', '$type')";
$result = mysql_query ($query);
			// Add the record to the database.
			//$query = "INSERT INTO notices (file_name, file_size, file_type) VALUES ('{$_FILES[$filename]['name']}', {$_FILES[$filename]['size']}, '{$_FILES[$filename]['type']}')";
			$result = mysql_query ($query);
		
			if ($result) {
				
				// Return the upload_id from the database.
				$upload_id = mysql_insert_id();
				
				// Move the file over.
				if (move_uploaded_file($_FILES[$filename]['tmp_name'], "./YEuploads/$upload_id")) {
				
					echo '<p>File number ' . ($i + 1) . ' has been uploaded!</p>';
					
				} else { // File could not be moved.
				
					echo '<p><font color="red">File number ' . ($i + 1) . ' could not be moved.</font></p>';
		
					// Remove the record from the database.
					$query = "DELETE FROM uploads WHERE upload_id = $upload_id";
					$result = mysql_query ($query);
				
					}
				
			//} else { // If the query did not run OK.
				//echo '<p><font color="red">Your submission could not be processed due to a system error. We apologize for any inconvenience.</font></p>'; 
				// Print the query and invoke the mysql_error() function to debug.
			}
			
			
			} else { // If the query did not run OK.
    echo '<p><font color="red">Your submission could not be processed due to a system error. We apologize for any inconvenience.</font></p>'; 
    echo mysql_errno() . ": " . mysql_error();
}

} // End of if (isset($the_file)...
		
}// End of FOR loop.
	
	mysql_close(); // Close the database connection.
		
//} // End of the main Submit conditional.
?>
<form enctype="multipart/form-data" action="add_file2.php" method="post">

	<fieldset><legend>Fill out the form to upload a file:</legend>
	<input type="hidden" name="MAX_FILE_SIZE" value="524288">
	
	<?php // Create the inputs.
	for ($i = 0; $i < $counter; $i++) {
		echo '<p><b>File:</b> <input type="file" name="upload' . $i . '" /></p>';
	}
	?>
	
	</fieldset>
	<input type="hidden" name="submitted" value="TRUE" />
	<div align="center"><input type="submit" name="submit" value="Submit" /></div>

</form>

Open in new window

0
Chris StanyonWebDevCommented:
OK. You seem to be trying to run the query twice (line 30 and line 33), and you've commented out the section that reports any database errors (line 55-57). They should look like:

} else { // If the query did not run OK.
    echo '<p><font color="red">Your submission could not be processed due to a system error. We apologize for any inconvenience.</font></p>'; 
    echo mysql_errno() . ": " . mysql_error();

Open in new window

0
Wanda MarstonCreative DirectorAuthor Commented:
One of those queries was commented out. When I added the error reporting I got a "No database selected".

So I added this line near the top of my script, which is in the mysql file and I still get the same error notice.

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

require ('./includes/config.inc.php');

require (MYSQL);

$connect = mysql_connect($hostname,$username,$password); 

$counter = 3; // Number of files to allow for.

Open in new window

0
Chris StanyonWebDevCommented:
Right. You're not selecting a database. You're making a connection to the server, but that's all. Once connected you need to actually choose a database to use. You might want to show us what's in the file referred to in the MYSQL constant. Generally, you would need to do:

$connect = mysql_connect($hostname,$username,$password);
mysql_select_db("name_of_your_database", $connect);

In the newer code (mysqli and PDO), you pass the database name in when making a connection, but with the outdated stuff you have to call it separately.
0
Wanda MarstonCreative DirectorAuthor Commented:
This is the code in the MYSQL file. The x's are actually filled in with the proper names and passwords

$hostname='xxxxxxxxx.netfirmsmysql.com'; 
$username='xxxx'; 
$password='xxxxx'; 
$database='xxxxx'; 
//establish database connection 
$connect = mysql_connect($hostname,$username,$password); 

Open in new window


This is what I have in another file. I realize that my coding in all files is older so I was actually hoping to backtrack and get it up to date. So this may be considered old as well.

	$q = "INSERT INTO users (username, email, pass, first_name, mid_initial, last_name, active, agree, date_expires) VALUES ('$u', '$e', '"  .  get_password_hash($p) .  "', '$fn', '$mi', '$ln', '1', 'Agree', DATE_ADD(NOW(), INTERVAL 2 YEAR) )";
			
			$r = mysqli_query ($connect, $q);

Open in new window

0
Chris StanyonWebDevCommented:
Right, the code in your MYSQL file is missing the db selection. You just need to add an additional line in there to actually select the db:

...
$database='xxxxx'; 
//establish database connection 
$connect = mysql_connect($hostname,$username,$password); 
mysql_select_db($database, $connect);

Open in new window

Once you've done that, remove the $connect = ... part from your upload script, otherwise you'll try and connect twice.

The code in your second snippet is better because you're using the mysqli library, but there's still a cleaner way of doing it (to prevent SQL Injection attacks). I'm guessing you've set up the $connect variable differently, otherwise it wouldn't work - you can't use a mysql_connect() against a mysqli_query()
0
Wanda MarstonCreative DirectorAuthor Commented:
Okay. Making great progress.

The three different upload files went into the database twice - all were at the exact same time 10:27 a.m. but only the last three upload_id's were in YEuploads folder. I am fairly certain that I did not hit the submit button twice.

Anyway, I DID get a message on the webpage saying that the three separate files had been uploaded.

Don't know if this would be a separate question or problem.
0
Chris StanyonWebDevCommented:
Excellent. I did say in a previous post that your were running the query twice, but you insisted it was commented out. It sounds very much like it wasn't. Look at this code snippet that you posted earlier:

$query = "INSERT INTO notices (file_name, file_size, file_type) VALUES ('$name', '$size', '$type')";
$result = mysql_query ($query);
// Add the record to the database.
//$query = "INSERT INTO notices (file_name, file_size, file_type) VALUES ('{$_FILES[$filename]['name']}', {$_FILES[$filename]['size']}, '{$_FILES[$filename]['type']}')";
$result = mysql_query ($query);

Open in new window

You're running the query twice - once on line 2 and again on line 5. Double check that code and make sure you're only running it one ( i.e. ONE call to $result = mysql_query(); )
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Wanda MarstonCreative DirectorAuthor Commented:
Thank you. I did more testing and the form as it is now appears to be working. Now I just have to figure out how to combine this with a form on another page which is working but has what one might call regular form fields that pertain to the same subject.

I think you went above and beyond what was required of you.
0
Chris StanyonWebDevCommented:
No worries Wanda. Glad I could help.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Databases

From novice to tech pro — start learning today.