Jump to content

how can i get this form and these file fields to submit simultaneously


Recommended Posts

HI,

I have a page in my admin system that allows users to write a post with a title and body text and a category. Ive just added an upload file system to it. Users browse and upload a file.

Ive added some javascript so that a user can create a new file upload box allowing the user to upload another file. The javascript adds an incremental number on to the end of the name and id tags within the input so i can identify them when im putting them in to the database.....

This is what i cant work out. The whole thing, including the uploaded files should be submitted the the db when the user clicks submit. How do i loop through each input field and input it in to the database? Im seeing problems on more than one level.

Firstly i need to attach the id of the blog entry on to each file, so i can pull it out later, but how can i do that because the blog entry is assigned its id as it gets put in the database by the primary key of its own table. How can i get this id on to each posted file?

Secondly, i cant think how to iterate through each posted file and input it in to the db. I think a while loop but i cant think how to do it.

These may seem like alarmingly easy questions with straightfoward answers but im still very new to this programming lark! Heres my code ( apologies the code ive posted is currently working with one button for the blog submittion and one for the file submittion, i have changed it so that both should be submitted from one button, ive also added a line of asterisks where the javascript would be creating more fields)

[code]<?php
session_start();
if (!isset($_SESSION['first_name'])) {
header ("Location:  http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "login.php");
exit(); // Quit the script.
}

else { $author = ($_SESSION['first_name']);}

include ('header.inc');

if(isset($_POST['submit'])) {


    if(isset($_POST['title'])) {
    $title = ($_POST['title']);
    }
    else {
    $title = NULL;
    }

    if(isset($_POST['body'])) {
    $body = ($_POST['body']);
    }
    else {
    $body = NULL;
    }

    if(isset($_POST['category_id'])) {
    $category_id = ($_POST['category_id']);
    }
    else {
    $category_id = NULL;
    }

if ($title && $body && $category_id) {

    require_once ('mysql_connect.php');
   
    $query = "INSERT INTO entries (blog_id, title, date_submitted, category_id, body, author_id) VALUES (NULL, '$title', NOW(), '$category_id', '$body', '$author')";
    $result = mysql_query ($query);


    if($result) {
      echo '<p>Inserted in to the database</p>';
      }

    else {
    echo '<p>there was an error</p>'; }
   
}



else {
    echo '<p>there was an error</p>'; }

}

echo '</form>';

?>


<div id="container" style="width: 507px; ">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p style="margin-bottom: 10px;">Write a New Post</p>

<p><label>title</label> <input type="text" class="text" name="title" size="35" maxlength="20" value="<?php if(isset($_POST['title'])) echo $_POST['title']; ?>" /></p>

<p><label>text</label><textarea name="body" style="margin-bottom: 20px;" rows="30" columns="150" value=""><?php if(isset($_POST['body'])) echo $_POST['body']; ?></textarea></p>
<div style="float: left;">


<p><label>category</label><select name="category_id" title="select a category"></p>
<?php

require_once ('mysql_connect.php');
$sql = "SELECT * FROM categories ORDER BY category_id";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
$cat_id = $row['category_id'];
$cat = $row['category'];





?>





<option value="<?php echo $cat_id; ?>"><?php echo $cat; ?></option>
<?php
}
?>
</select></p>







<input type="submit" class="submit" name="submit" value="submit post" />
</div>




<?php
if(isset($_POST['cat'])) {
$cat = $_POST['cat'];
}

if($cat) {

require_once ('mysql_connect.php');
   
$sql = "INSERT INTO categories (category_id, category) VALUES (NULL, '$cat')";
$result = mysql_query ($sql);
}



?>
<div style="float: right;s">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p><label>Create a new category</label> <input type="text" class="text" name="cat" size="35" maxlength="20" value="" /></p>
<input type="submit" class="submit" name="submitcat" value="create" />
<?php
if (isset($_POST['submit_media'])) { // Handle the form.

require_once ('mysql_connect.php'); // Connect to the database.

// Function for escaping and trimming form data.
function escape_data ($data) {
global $dbc;
if (ini_get('magic_quotes_gpc')) {
$data = stripslashes($data);
}
return mysql_real_escape_string (trim ($data), $dbc);
} // End of escape_data() function.

// Check for a description (not required).
if (!empty($_POST['description'])) {
$d = escape_data($_POST['description']);
} else {
$d = '';
}

// Add the record to the database.
$query = "INSERT INTO uploads (file_name, file_size, file_type, description, upload_date, blog_id) VALUES ('{$_FILES['upload']['name']}', {$_FILES['upload']['size']}, '{$_FILES['upload']['type']}', '$d', NOW(), )";
$result = @mysql_query ($query);

if ($result) {

// Create the file name.
$extension = explode ('.', $_FILES['upload']['name']);
$uid = mysql_insert_id(); // Upload ID
$filename = $uid . '.' . $extension[1];

// Move the file over.
if (move_uploaded_file($_FILES['upload']['tmp_name'], "uploads/$filename")) {
echo '<p>The file has been uploaded!</p>';
} else {
echo '<p><font color="red">The file could not be moved.</font></p>';

// Remove the record from the database.
$query = "DELETE FROM uploads WHERE upload_id = $uid";
$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>';
}

mysql_close(); // Close the database connection.

} // End of the main Submit conditional.
?>
<br /><br />
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">


<label>
Upload a file
</label>
<fieldset id="fs">
<button onclick="addfield(); return false;">Add another file</button>
<input class="text" type="file" name="field1" id="field1" />
****************************************************
<input type="hidden" name="MAX_FILE_SIZE" value="524288">
</fieldset>
<div align="center"><input type="submit" class="submit_media" name="submit" value="Submit" /></div>



</form><!-- End of Form -->


</div>
</div>










 




<?php include ('footer.inc'); ?>


   

   

    [/code]
OK...

Firstly, don't get the javascript to add a new field with an incremented name and number, get it to create a new field with the same name, so your form finishes up looking a little like this...

[code]<input type="file" name="blogfile[]" id="blogfile[]">
<input type="file" name="blogfile[]" id="blogfile[]">
<input type="file" name="blogfile[]" id="blogfile[]">
<input type="submit" name="submit" id="submit" value="Post Blog">[/code]

This way, when you get into php, the files will be in an array, as opposed to individual variables and it'll be a whole lot easier to loop through.

I have to rush off now, but that should get you started and to get the id of the blog entry you'll want to use [url=http://uk.php.net/manual/en/function.mysql-insert-id.php]mysql_insert_id()[/url].

Look that up and I'll check back in about an hour as I have to go out now.

Regards
Huggie
hi thanks for the reply!

right i got the javascript doing what you said and ive tried to merge my two queries so they both wokr off of one submit but im getting a parese error on the last line of my script. I also cant think how to loop through all those input fields/use the mysql_insert_id at this point of the script. Ive never tried to do two queries simultaneously before so i dont even know if its right. Any chance you could take a peek?

[code]<?php
session_start();
if (!isset($_SESSION['first_name'])) {
header ("Location:  http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "login.php");
exit(); // Quit the script.
}

else { $author = ($_SESSION['first_name']);}

include ('header.inc');

if(isset($_POST['submit'])) {


    if(isset($_POST['title'])) {
    $title = ($_POST['title']);
    }
    else {
    $title = NULL;
    }

    if(isset($_POST['body'])) {
    $body = ($_POST['body']);
    }
    else {
    $body = NULL;
    }

    if(isset($_POST['category_id'])) {
    $category_id = ($_POST['category_id']);
    }
    else {
    $category_id = NULL;
    }

if ($title && $body && $category_id) {

    require_once ('mysql_connect.php');
   
    $query = "INSERT INTO entries (blog_id, title, date_submitted, category_id, body, author_id) VALUES (NULL, '$title', NOW(), '$category_id', '$body', '$author')";
    $result = mysql_query ($query);


    if($result) {
      echo '<p>Inserted in to the database</p>';
      }

    else {
    echo '<p>there was an error</p>'; }
   
}



else {
    echo '<p>there was an error</p>'; }

}

echo '</form>';

?>


<div id="container" style="width: 507px; ">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p style="margin-bottom: 10px;">Write a New Post</p>

<p><label>title</label> <input type="text" class="text" name="title" size="35" maxlength="20" value="<?php if(isset($_POST['title'])) echo $_POST['title']; ?>" /></p>

<p><label>text</label><textarea name="body" style="margin-bottom: 20px;" rows="30" columns="150" value=""><?php if(isset($_POST['body'])) echo $_POST['body']; ?></textarea></p>
<div style="float: left;">


<p><label>category</label><select name="category_id" title="select a category"></p>
<?php

require_once ('mysql_connect.php');
$sql = "SELECT * FROM categories ORDER BY category_id";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
$cat_id = $row['category_id'];
$cat = $row['category'];





?>





<option value="<?php echo $cat_id; ?>"><?php echo $cat; ?></option>
<?php
}
?>
</select></p>







<input type="submit" class="submit" name="submit" value="submit post" />
</div>




<?php
if(isset($_POST['cat'])) {
$cat = $_POST['cat'];
}

if($cat) {

require_once ('mysql_connect.php');
   
$sql = "INSERT INTO categories (category_id, category) VALUES (NULL, '$cat')";
$result = mysql_query ($sql);
}



?>
<div style="float: right;s">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p><label>Create a new category</label> <input type="text" class="text" name="cat" size="35" maxlength="20" value="" /></p>
<input type="submit" class="submit" name="submitcat" value="create" />
<?php
if (isset($_POST['submit_media'])) { // Handle the form.

require_once ('mysql_connect.php'); // Connect to the database.

// Function for escaping and trimming form data.
function escape_data ($data) {
global $dbc;
if (ini_get('magic_quotes_gpc')) {
$data = stripslashes($data);
}
return mysql_real_escape_string (trim ($data), $dbc);
} // End of escape_data() function.

// Check for a description (not required).
if (!empty($_POST['description'])) {
$d = escape_data($_POST['description']);
} else {
$d = '';
}

// Add the record to the database.
$query = "INSERT INTO uploads (file_name, file_size, file_type, description, upload_date, blog_id) VALUES ('{$_FILES['upload']['name']}', {$_FILES['upload']['size']}, '{$_FILES['upload']['type']}', '$d', NOW(), )";
$result = @mysql_query ($query);

if ($result) {

// Create the file name.
$extension = explode ('.', $_FILES['upload']['name']);
$uid = mysql_insert_id(); // Upload ID
$filename = $uid . '.' . $extension[1];

// Move the file over.
if (move_uploaded_file($_FILES['upload']['tmp_name'], "uploads/$filename")) {
echo '<p>The file[/code]
sorry i made a stupid mistake. The code works now but when i print_r the post and file arrays i only get results from the post. The file bits just returnng this:


Array ( [title] => ijijiji [body] => jijijijijijijijijijij [MAX_FILE_SIZE] => 524288 [submit] => submit post [category_id] => 31 [cat] => ) Array ( [field] => Array ( [name] => Array ( [0] => change.php ) [type] => Array ( [0] => application/octet-stream ) [tmp_name] => Array ( [0] => /var/tmp/php9uf7zv ) [error] => Array ( [0] => 0 ) [size] => Array ( [0] => 3719 ) ) )

and my new code:

[code]<?php
session_start();
if (!isset($_SESSION['first_name'])) {
header ("Location:  http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "login.php");
exit(); // Quit the script.
}

else { $author = ($_SESSION['first_name']);
}

include ('header.inc');

if(isset($_POST['submit'])) {


    if(isset($_POST['title'])) {
    $title = ($_POST['title']);
    }
    else {
    $title = NULL;
    }

    if(isset($_POST['body'])) {
    $body = ($_POST['body']);
    }
    else {
    $body = NULL;
    }

    if(isset($_POST['category_id'])) {
    $category_id = ($_POST['category_id']);
    }
    else {
    $category_id = NULL;
    }

if ($title && $body && $category_id) {

    require_once ('mysql_connect.php');
   
    $query = "INSERT INTO entries (blog_id, title, date_submitted, category_id, body, author_id) VALUES (NULL, '$title', NOW(), '$category_id', '$body', '$author')";
    $result = mysql_query ($query);

      $sql = "INSERT INTO uploads (file_name, file_size, file_type, upload_date) VALUES ('{$_FILES['upload']['name']}', {$_FILES['upload']['size']}, '{$_FILES['upload']['type']}', '$d', NOW() )";
    $query = @mysql_query ($sql);

if ($query) {

// Create the file name.
$extension = explode ('.', $_FILES['upload']['name']);
$uid = mysql_insert_id(); // Upload ID
$filename = $uid . '.' . $extension[1];

// Move the file over.
if (move_uploaded_file($_FILES['upload']['tmp_name'], "uploads/$filename")) {
echo '<p>The file has been uploaded!</p>';
} else {
echo '<p><font color="red">The file could not be moved.</font></p>';

// Remove the record from the database.
$query = "DELETE FROM uploads WHERE upload_id = $uid";
$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_r($_POST);

print_r($_FILES);


// End of the main Submit conditional.


echo '</form>';

?>


<div id="container" style="width: 507px; ">
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p style="margin-bottom: 10px;">Write a New Post</p>

<p><label>title</label> <input type="text" class="text" name="title" size="35" maxlength="20" value="<?php if(isset($_POST['title'])) echo $_POST['title']; ?>" /></p>

<p><label>text</label><textarea name="body" style="margin-bottom: 20px;" rows="30" columns="150" value=""><?php if(isset($_POST['body'])) echo $_POST['body']; ?></textarea></p>
<div style="float: left;">
<label>
Upload a file
</label>
<fieldset id="fs">
<button onclick="addfield(); return false;">Add another file</button>
<input class="text" type="file" name="field[]" id="field[]" />
<input type="hidden" name="MAX_FILE_SIZE" value="524288">
<input type="submit" class="submit" name="submit" value="submit post" />
</fieldset>



<p><label>category</label><select name="category_id" title="select a category"></p>
<?php

require_once ('mysql_connect.php');
$sql = "SELECT * FROM categories ORDER BY category_id";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
$cat_id = $row['category_id'];
$cat = $row['category'];





?>





<option value="<?php echo $cat_id; ?>"><?php echo $cat; ?></option>
<?php
}
?>
</select></p>








</div>





<?php
if(isset($_POST['submitcat'])) {
$cat = $_POST['submitcat'];
}

if($cat) {

require_once ('mysql_connect.php');
   
$sql = "INSERT INTO categories (category_id, category) VALUES (NULL, '$cat')";
$result = mysql_query ($sql);
}



?>
<div style="float: right;s">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p><label>Create a new category</label> <input type="text" class="text" name="cat" size="35" maxlength="20" value="" /></p>
<input type="submit" class="submit" name="submitcat" value="create" />
</div>
</div>     [/code]


any ideas?
You're using code like this...

[code=php:0]$extension = explode ('.', $_FILES['upload']['name']);[/code]

But your file field in the form is called 'field' so you should be using:

[code=php:0]$extension = explode ('.', $_FILES['field']['name']);[/code]

Regards
Huggie
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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