I have a form wherein each input is contained within array items[]
. This array contains both text inputs and file inputs. If that's already a huge red flag, then TLDR - can an array containing both text and file inputs be passed to the same SQL statement for database upload?
I have an echo statement in my PHP where I try to echo the names of the inputs, "paragraph" and "image". "paragraph" is a text input, and "image" is a file input.
foreach($_POST['items'] as $index => $item){
$key = key($item);
echo $key;
....
^ This echoes "paragraph", but does not echo "image".
For a bit more clarity, here is the form:
<form method="post" action="insert.php" enctype="multipart/form-data">
<textarea name="title"></textarea>
<!--paragraph input-->
<div><textarea name="items[][paragraph]"></textarea></div>
<!--paragraph input-->
<div><textarea name="items[][paragraph]"></textarea></div>
<!--paragraph input-->
<div><textarea name="items[][paragraph]"></textarea></div>
<!--file input-->
<div><input type="file" name="items[][image]" id="uploadImage" multiple></div>
<!--file input-->
<div><input type="file" name="items[][image]" id="uploadImage" multiple></div>
<!--file input-->
<div><input type="file" name="items[][image]" id="uploadImage" multiple></div>
<input type="submit" name="upload" value="Upload" id="upload">
</form>
...and the php. There is no handling of the file type and storing it in a directory yet since I'm just trying to see if it's possible for the foreach
to recognize the file input.
<?php
if (isset($_POST['upload'])) {
$host = "";
$dbname = "";
$user = "";
$pass = "";
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $db->prepare("INSERT INTO table (placement, datatype, typetext) VALUES (:placement, :datatype, :typetext)");
if($statement){
if(is_array($_POST['items'])){
foreach($_POST['items'] as $index => $item){
//this is where I'm trying to catch the names of
//the inputs, "paragraph" and "image". This will
// print "paragraph", but will NOT print "image"
$key = key($item);
echo $key;
$statement->execute(['placement' => $index, 'datatype' => key($item), 'typetext' => $item[key($item)]]);
}
}
}
$db = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
exit(header("location: insert.php"));
}
?>
I'm guessing that, because the foreach
contains $_POST['items']
and not something like $_FILES['items']
, this will not work. Is that the case? The main reason I have everything inside of the array items[]
is so that I can store an index of these items within the database, so that when I retrieve the contents of a single post, I can place them in the correct order. If I'm going about this the wrong way, what is a better way to do this?