I am trying to upload a CSV file which contains the fields stated in the link below [see CSV example] via a web form. The user can browse their computer by clicking the upload button, select their CSV file and then click upload which then imports the CSV data into the database in their corresponding fields. At the moment when the user uploads their CSV file, the row is empty and doesn't contain any of the data that the CSV file contains. Is there a way i could solve this so that the data inside the CSV file gets imported to the database and placed in its associating fields?
CSV example:
http://i754.photobucket.com/albums/xx182/rache_R/Screenshot2014-04-10at145431_zps80a42938.png
uploads.php
<!DOCTYPE html>
<head>
<title>MySQL file upload example</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file"><br>
<input type="submit" value="Upload file">
</form>
<p>
See all files
</p>
</body>
</html>
upload_file.php
<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'vario007', 'spineless');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$filedata= file_get_contents($_FILES ['uploaded_file']['tmp_name']); //this imports the entire file.
// Create the SQL query
$query = "
INSERT INTO `Retail` (
`date`, `order_ref`, `postcode`, `country`, `quantity`, `packing_price`, `dispatch_type`, `created`
)
VALUES (
'{$date}', '{$order_ref}', '{$postcode}', '{$country}', '{$quantity}', '{$packing_price}', '{$dispatch_type}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>
try this
<?php
if(isset($_FILES['uploaded_file'])) {
if($_FILES['uploaded_file']['error'] == 0) {
$dbLink = new mysqli('localhost', 'root', 'vario007', 'spineless');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
$file = $_FILES ['uploaded_file']['tmp_name'];
$handle = fopen($file, "r");
$row = 1;
while (($data = fgetcsv($handle, 0, ",","'")) !== FALSE)
{
if($row == 1)
{
// skip the first row
}
else
{
//csv format data like this
//$data[0] = date
//$data[1] = order_ref
//$data[2] = postcode
//$data[3] = country
//$data[4] = quantity
//$data[5] = packing_price
//$data[6] = dispatch_type
$query = "
INSERT INTO `Retail` (
`date`, `order_ref`, `postcode`, `country`, `quantity`, `packing_price`, `dispatch_type`, `created`
)
VALUES (
'".$data[0]."', '".$data[1]."', '".$data[2]."', '".$data[3]."', '".$data[4]."', '".$data[5]."', '".$data[6]."', NOW()
)";
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
$row++;
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>
fgetcsv() in third argument in separator to you want to save in csv file. Ex: comma,semicolon or etc.
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$filedata= csv_to_array($_FILES ['uploaded_file']['tmp_name']);
foreach($filedata as $data)
{
$sql = "INSERT into table SET value1='".$data['value1']."'......";
}
Related
No error messages appear on the page. Upload File button works. Upload button doesn't trigger db insert but the page refreshes as if it did.
I am not sure if the array of data from Excel is being coded correctly on the INSERT Into command. Any help is appreciated but PLEASE keep it simple. I am not a seasoned developer. Very green and primarily use procedural coding. If you use an experienced term, don't assume I know what it means.
PHP - if Post Submit button code. The errorMsg doesn't display if no file is attached and submit button is clicked
var_dump($_POST);
if (isset($_POST['submit'])) {
//print_r($_FILES);
$ok = 'true';
$file = $_FILES['csv_file']['tmp_name'];
$handle = fopen($file, "r");
echo ++$x;
if ($handle !== FALSE){
$errorMsg = "<br /><div align='center'><font color='red'>Please select a CSV file to import</font></div>";
$ok = 'false';
echo ++$x;
PHP continued - I'm not seeing the uploaded file populate the database
} else {
print_r(fgetcsv($handle));
while(($filesop = fgetcsv($handle, 1000, ",")) !== FALSE){
$email = mysqli_real_escape_string($con_db, $filesop[0]);
$f_name = mysqli_real_escape_string($con_db, $filesop[1]);
$l_name = mysqli_real_escape_string($con_db, $filesop[2]);
$password = md5(mysqli_real_escape_string($con_db, $filesop[3]));
$zipcode = mysqli_real_escape_string($con_db, $filesop[4]);
$co_id = mysqli_real_escape_string($con_db, $filesop[5]);
$employee = mysqli_real_escape_string($con_db, $filesop[6]);
$assessment_ct = mysqli_real_escape_string($con_db, $filesop[7]);
echo ++$x;
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if ( strlen($email) > 0) {
echo ++$x;
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo ++$x;
$ok = 'false';
$errorMsg .= 'E-mail address is not correct';
}
}
// error handling for password
if (strlen($password) >= 5) {
echo ++$x;
$ok = 'true';
} else {
echo ++$x;
$ok = 'false';
$errorMsg .= 'Your password is too short (please use at least 5 characters)';
}
// If the tests pass we can insert it into the database.
if ($ok == 'true') {
echo ++$x;
$sql = mysqli_query($con_db, "INSERT INTO `myMembers` (email, f_name, l_name, password, zipcode, co_id, employee, assessment_ct) VALUES ('$email', '$f_name', '$l_name', '$password', '$zipcode', '$co_id', '$employee', '$assessment_ct')") or die ("Shit is not working");
} else {// close if $ok == 'true'
$result = print_r($handle);
echo $handle.'<br>';
echo ++$x;
}
} // close WHILE LOOP
fclose($handle);
if ($sql !== FALSE) {
echo ++$x;
$successMsg = 'Your database has imported successfully!';
//print_r($_FILES);
//header('excel_import.php');
} else {
echo ++$x;
$errorMsg = 'Sorry! There is some problem in the import file.';
//print_r($_FILES);
//header('excel_import.php');
}
} // close if (!is_null($file)){
} // close if $post = submit
HTML Code for the form to submit uploaded file
<form enctype="multipart/form-data" method="POST" action="excel_import.php">
<div align="center">
<label>File Upload: </label><input type="file" id="csv_file" accept=".csv" >
<p>Only Excel.CSV File Import</p>
<input type="submit" name="csv_file" class="btn myButton" value="Upload">
</div>
</form>
</div>
<div><?php echo $errorMsg; ?><?php echo $successMsg; ?></div>
Your submit button does not have a name - and thus $_POST['submit'] is not set. Also, fclose($file) should be fclose($handle). And you should be checking with $handle !== FALSE and $sql !== FALSE rather than with is_null().
I am trying to upload excel .xls file but got an error when I am trying to import autoload file my web page going blank and when I comment it its works. I can't Import file of spout extenstion of reader. Here this is my code.
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;
require_once 'http://localhost/muddy/admin/spout-2.7.2/src/Spout/Autoloader/autoload.php';//Error cant import
here in this require once cant upload file if I write this code my web page going blank !
if (!empty($_FILES['file']['name'])) {
echo "ks";
$pathinfo = pathinfo($_FILES["file"]["name"]);
if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
&& $_FILES['file']['size'] > 0 ) {
$inputFileName = $_FILES['file']['tmp_name'];
// Read excel file by using ReadFactory object.
$reader = ReaderFactory::create(Type::XLSX);
// Open file
$reader->open($inputFileName);
$count = 1;
foreach ($reader->getSheetIterator() as $sheet) {
echo "ks22";
// Number of Rows in Excel sheet
foreach ($sheet->getRowIterator() as $row) {
echo "ks32";
// It reads data after header. In the my excel sheet,
// header is in the first row.
if ($count > 1) {
echo "ks4";
// Data of excel sheet
$data['Member_no'] = $row[0];
$data['Member_name'] = $row[1];
$data['Gender'] = $row[2];
$data['Club_name'] = $row[3];
$data['member_since'] = $row[4];
$data['Expiry_date'] = $row[3];
$member_no = $data['Member_no'];
$member_name = $data['Member_name'];
$gender = $data['Gender'];
$club_name = $data['Club_name'];
$member_since = $data['member_since'];
$expiry_date = $data['Expiry_date'];
$query="INSERT INTO `mmholdin_management`.`Club_member` (Member_no`, `Member_name`, `Gender`, `Club_name`, `member_since`, `Expiry_date`) VALUES ($member_no ,$member_name, $gender,$club_name,$member_since,$expiry_date)";
echo $query;
if(mysql_query($query))
{
$msg = "Record Saved!";
//header("Location:managecustomer.php");
exit;
}
else
{
$msg = "Unable to Save!";
}
print_r(data);
}
$count++;
}
}
// Close excel file
$reader->close();
} else {
echo "Please Select Valid Excel File";
}
} else {
//echo "Please Select Excel File";
}
try this example.
$file = "your-file.xls";
$handle = fopen($file, "r");
$c = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$name = $filesop[0];
$email = $filesop[1];
$sql = mysql_query("INSERT INTO xls (name, email) VALUES ('$name','$email')");
}
if($sql){
echo "You database has imported successfully";
}else{
echo "Sorry! There is some problem.";
}
check this: https://www.studytutorial.in/how-to-upload-or-import-an-excel-file-into-mysql-database-using-spout-library-using-php
Here I am uploading single file to the database and I used longblob, how can I change this code to upload multiple files to database with same id and also I can able to download more than one uploaded files for the same id in download option. Can anyone please help me?
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '12345', 'documentksrsac');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
//$project_name = $_POST["pname"];
//$project_name = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['project_name']));
// $project_name =real_escape_string(['uploaded_file']['project_name']);
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `fileupload1` (
`name`, `mime`, `size`, `data`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}'
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// close connection
//mysqli_close($link);
?>
For multiple Image uploading I am using given code:-
<form method="post" enctype="multipart/form-data">
<input type="file" name="img[]" >
<input type="file" name="img[]" >
<input type="file" name="img[]" >
<input type="file" name="img[]" >
<button type="submit" name="save" >Submit</button>
</form>
<?php
if(isset($_POST['save']))
{
$img_name=$_FILES['img']['name'];
$img_type=$_FILES['img']['type'];
$img_temp_name=$_FILES['img']['tmp_name'];
$img_size=$_FILES['img']['size'];
$count=count($img_name);
for($i=0; $i<$count; $i++){
$name=$img_name[$i];
$type=$img_type[$i];
$temp_name=$img_temp_name[$i];
$size=$img_size[$i];
$query = "INSERT INTO `fileupload1` (`name`, `mime`, `size`, `data`)VALUES ('{$name}', '{$type}', {$temp_name}, '{$size}')";
$result = $dbLink->query($query);
}
}
I am trying to upload a file to an images folder and also insert the directory path into a mysql db.
Here is my HTML form
<form enctype="multipart/form-data" method="post" action="newfacility.php">
<fieldset>
<legend>New Facility</legend>
...
<label for="photo">Facility Photo:</label>
<input type="file" id="facilityphoto" name="facilityphoto" /><br />
<label for="province">Photo Description:</label>
<input type="text" id="photodesc" name="photodesc" /><br />
....
<input type="submit" value="Create" name="submit" />
</fieldset>
</form>
newfacility.php
require_once('../appvars.php');
require_once('upload_image.php');
//connect to db and test connection.
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['submit'])) {
// Grab the user data from the POST
$facilityNumber = mysqli_real_escape_string($dbc, trim($_POST['facilitynumber']));
....
....
//This is defined in appvars.php -- define('MM_UPLOADPATH', 'images/');
//facility photo
$facilityPhoto = MM_UPLOADPATH . basename($_FILES["facilityphoto"]["name"]);
$facilityPhotoDesc = mysqli_real_escape_string($dbc, trim($_POST['photodesc']));
// check if the faciliy info already exists.
if (!empty($facilityNumber) && !empty($facilityName) && !empty($facilityAddress) && !empty($facilityCity)) {
$query = "SELECT * FROM facility WHERE facility_number = '$facilityNumber' AND facility_name = '$facilityName' "
. "AND facility_address = '$facilityAddress' AND facility_city = '$facilityCity'";
$data = mysqli_query($dbc, $query);
//if the facility is unique insert the data into the database
if (mysqli_num_rows($data) == 0) {
//insert into facility table
$query = "INSERT INTO facility (facility_id, account_id, facility_number, facility_name, facility_address,"
. " facility_city, facility_province, facility_postal_code, facility_photo, facility_roof_plan,"
. " facility_roof_size, facility_roof_size_inspected, facility_last_inspected_date, facility_inspected_by)"
. " VALUES (NULL, '$selectedAssocAccount', '$facilityNumber', '$facilityName', '$facilityAddress', "
. "'$facilityCity', '$facilityProvince', '$facilityPostalCode', '$facilityRoofSize', "
. "'$facilityRoofSizeInspected', '$facilityDayInspected', '$facilityInspectedBy')";
mysqli_query($dbc, $query);
//query used to get the facility_id of the facility we had just entered -- I haven't tested this yet.
$getFacilityID = "SELECT facility_id FROM facility WHERE facility_number = '$facilityNumber' AND facility_name = '$facilityName' "
. "AND facility_address = '$facilityAddress' AND facility_city = '$facilityCity'";
$facilityID = mysqli_query($dbc, $getFacilityID);
//insert into photo table
$photoQuery = "INSERT INTO photo (photo_id, facility_id, photo, photo_desc)"
. "VALUES (NULL, $facilityID, $facilityPhoto, $facilityPhotoDesc)";
mysqli_query($dbc, $photoQuery);
// Confirm success with the user
echo '<p>You have succesfully created a new facility. '
. 'Please go back to the admin panel.</p>';
//testing to see if I can view the image
echo '<img class="profile" src="' . MM_UPLOADPATH . $facilityPhoto . '"/>';
//close db connection
mysqli_close($dbc);
exit();
}
And finally here is upload_image.php
if(isset($_FILES["facilityphoto"])) {
// Check if file already exists
if (file_exists($facilityPhoto)) {
echo "Sorry, facility photo already exists.";
}
if($_FILES['facilityphoto']['error'] !==0) {
echo "Error uploading facility photo image.";
} else {
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)) {
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading the facility photo.";
}
}
}
So the error I keep hitting right now is: echo "Sorry, there was an error uploading the facility photo.";
I don't understand what I am doing wrong here that is resulting in the image not being uploaded into my images/ directory.
I am going to provide an answer that addresses only the file upload problem, all the database stuff is striped from the answer as it is not relevant.
// returns true only if the file was written to $to,
// the value of $status_msg will be a user friendly string
// representing the outcome.
function save_facility_photo($from, $to, &$status_msg) {
// Check if file already exists
if (file_exists($to)) {
$status_msg = "Sorry, facility photo already exists.";
return false;
}
if (move_uploaded_file($from, $to)) {
$status_msg = "The file ".basename($to)." has been uploaded.";
return true;
}
$status_msg = "Sorry, there was an error uploading the facility photo.";
return false;
}
if (isset($_POST['submit'])) {
define('MM_UPLOADPATH', 'images/');
$facilityPhoto = MM_UPLOADPATH . basename($_FILES["facilityphoto"]["name"]);
if ($_FILES['facilityphoto']['error'] == UPLOAD_ERR_OK) {
$status_msg = '';
$from = $_FILES["facilityphoto"]["tmp_name"];
$saved = save_facility_photo($from, $facilityPhoto, $status_msg);
}
else {
// handle upload error
}
// continue with code
}
The following is an explanation of what I think is happening in your scripts.
At the top of newfacility.php, require_once('upload_image.php'); is called. Now lets step though upload_image.php noting that $facilityPhoto has not yet been defined
// this is very likely true
if(isset($_FILES["facilityphoto"])) {
// $facilityPhoto is undefined so file_exists(NULL) will return false
if (file_exists($facilityPhoto)) { }
// the image upload was probably successful, so we jump to the else branch
if($_FILES['facilityphoto']['error'] !==0) {
}
else {
// $facilityPhoto is undefined move_uploaded_file('p/a/t/h', NULL)
// will return false, so we jump to the else branch
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)) {
}
else {
// resulting in this error
echo "Sorry, there was an error uploading the facility photo.";
}
}
}
Replace these lines:
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)){
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
}
with these:
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], 'images/'. $_FILES["facilityphoto"]["name"])){
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
}
im having a problem with my code in uploading and displaying images.. well I am planning to redirect the page after the upload process is done so I used a header function but gave warning and errors and unfortunately failed the upload.. how can I remove it? here's the code..
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
//file properties//
$file = $_FILES['image']['tmp_name'];
echo '<br />';
/*if(!isset($file))
echo "Please select your images";
else
{
*/for($count = 0; $count < count($_FILES['image']); $count++)
{
//$image = file_get_contents($_FILES['image']['tmp_name']);
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]); echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results)
echo "Problem uploding the image. Please check your database";
//else
//{
echo "";
//$last_id = mysql_insert_id();
//echo "Image Uploaded. <p /> <p /><img src=display.php? id=$last_id>";
//header('Lcation: display2.php?id=$last_id');
}
//}
}
mysql_close($con);
header('Location: fGallery.php');
?>
the header function supposedly directs me to another page that would make a gallery.. here is the code..
<?php
//connect to the database//
mysql_connect("localhost","root", "") or die(mysql_error());
mysql_select_db("imagedatabase") or die(mysql_error());
//requesting image id
$image = mysql_query("SELECT * FROM images ORDER BY id DESC");
while($row = mysql_fetch_assoc($image))
{
foreach ($row as $img) echo '<img src="img.php?id='.$img["id"].'">';
}
mysql_close();
?>
I have also a problem with my gallery .. some help will be GREAT! THANKS! :D
The header() function must be called before any other echo or die calls which produce output.
You may could buffer your outputs if you need the output, but in your case it makes no difference because the output will never be shown to the user. The browser will read the redirect and navigate to the second page.
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con) {
// this output is okay the redirect will never be reached.
die('Could not connect to the database:' . mysql_error());
// remember after a die this message will never be shown!
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel) {
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION"; // same here with the die!
}
//file properties//
$file = $_FILES['image']['tmp_name'];
// OUTPUT
// echo '<br />';
// removed out commented code
for($count = 0; $count < count($_FILES['image']); $count++)
{
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]);
// OUTPUT
// echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
// you may better use a die if you want to prevent the redirection
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results) // use die
echo "Problem uploding the image. Please check your database";
// OUTPUT
// echo "";
}
}
mysql_close($con);
header('Location: fGallery.php');
?>
Above I marked every output for you and also removed all outcomments lines.
You've got a header error because you printed out <br /> before the header function. In order to use the header function you can't print out any information before it. That's why you're getting the error.
Regarding your gallery the foreach loop is unnecessary. You can change the code to this:
while($row = mysql_fetch_assoc($image)) {
echo '<img src="img.php?id='.$row["id"].'">';
}
You can use ob_start() to get data in buffer.