Jump to content

foreach loop prob


drisate

Recommended Posts

Hey guys i have a problem ... I created a javascript that auto generates form filds to upload MP3. The generated fields looks like this:

 

<div id="new_link_fields0">
<div id="form_source0">
	<span class="r">Nom: <input name="nom_0"><input type="hidden" value="1" name="i[]">
	<input type="file" size="30" name="mp3_0"><br> </span></div>
<div id="form_source1">
	<span class="r">Nom: <input name="nom_1"><input type="hidden" value="1" name="i[]">
	<input type="file" size="30" name="mp3_1"><br> </span></div>
<div id="form_source2">
	<span class="r">Nom: <input name="nom_2"><input type="hidden" value="1" name="i[]">
	<input type="file" size="30" name="mp3_2"><br> </span></div>
<div id="form_source3">
	<span class="r">Nom: <input name="nom_3"><input type="hidden" value="1" name="i[]">
	<input type="file" size="30" name="mp3_3"><br> </span></div>
<div id="form_source4">
	<span class="r">Nom: <input name="nom_4"><input type="hidden" value="1" name="i[]">
	<input type="file" size="30" name="mp3_4"><br> </span></div>
</div>

 

Then i use

$i=0;
foreach ($_POST[i] as $value){

$file_name = $_FILES['mp3']['name'][$i];
$file_tmp = $_FILES['mp3']['tmp_name'][$i];

echo "The file ".$file_name." is number $i<br>";
}

 

But it returns

 

The file djj.mp3 is number 0

The file  is number 1

The file  is number 2

The file  is number 3

The file  is number 4

 

only the first loop is working ... what did i do wroung?

Link to comment
https://forums.phpfreaks.com/topic/105653-foreach-loop-prob/
Share on other sites

That form will not give you the arrays you're trying to use.

 

Do a

<?php
echo '<pre>$_POST:' . print_r($_POST,true) . '</pre>';
echo '<pre>$_FILES:' . print_r($_FILES,true) . '</pre>';
?>

at the start of the processing script to see what's being returned.

 

See if this code is helpful:

<?php
if (isset($_POST['submit']))
echo '<pre>' . print_r($_POST,true) . print_r($_FILES,true) . '</pre>';
?>
<body>
<form action="" method="post" enctype="multipart/form-data">
<div id="new_link_fields0">
<?php
for ($i=0;$i<5;$i++) {
?>	<div id="form_source<?php echo $i ?>">
	<span class="r">Nom: <input name="nom[<?php echo $i ?>]"><input type="hidden" value="<?php echo $i ?>" name="i[<?php echo $i ?>]">
	<input type="file" size="30" name="mp3[<?php echo $i ?>]"><br> </span></div>
<?php } ?>
</div>
<input type="submit" name="submit" value="Upload">
</body>

 

Ken

 

Link to comment
https://forums.phpfreaks.com/topic/105653-foreach-loop-prob/#findComment-541327
Share on other sites

That would probably work kenrbnsn but i really need to use the auto form generater ... take a look save this to an HTML page and open it.

 

<script type="text/javascript">
var fields;

function HTMLBlock(el) {
var instance = 1, elementNames = [], i, item, container;

/* remove source element */
container = el.parentNode;
container.removeChild(el);

/* cache input elements' name attributes */
for (i = 0; item =
el.getElementsByTagName("input").item(i); i++) {
elementNames[i] = item.getAttributeNode("name");
}

/* method to modify and insert a clone of the original element */
this.insert = function () {
for (var i = elementNames.length; i--; ) {
/* replace digits with instance # */
elementNames[i].nodeValue =
elementNames[i].nodeValue.replace(/\d+/, instance);
}
instance++;
container.appendChild(el.cloneNode(true));
};
}

function createHTMLBlock(id) {
var d = document, el;

/* test browser supports the methods we'll be using */
if (d.getElementById && (el = d.getElementById(id)) &&
el.getElementsByTagName && el.cloneNode &&
el.getAttributeNode) {
/* ... etc. */
return new HTMLBlock(el); // yes
}
return null; // no
}

function addHTML() {
if (fields) {
fields.insert();
}
}
</script>

<center><input type="button" onclick="addHTML()" value="Add Fields"></center><br>

<div id="new_link_fields"><div id="form_source"><span class="r">Nom: <input type='text' name='nom[]' value='' size='20'><input type='hidden' name='i[]' value='1'> <input type='file' name='mp3[]' size='30'><br></span></div></div>

<script type="text/javascript">
/* remove the HTML and set up the object down here, before
anything's displayed */
fields = createHTMLBlock("form_source");
</script>

It's a really cool script

Link to comment
https://forums.phpfreaks.com/topic/105653-foreach-loop-prob/#findComment-541334
Share on other sites

It returned

 

Modifier un albume  Ajouter des MP3 


$_POST:Array
(
    [nom] => Array
        (
            [0] => g
            [1] => g
            [2] => g
        )

    [i] => Array
        (
            [0] => 1
            [1] => 1
            [2] => 1
        )

    [btn_name3] => Suivant
)
$_FILES:Array
(
    [mp1] => Array
        (
            [name] => Array
                (
                    [0] => 782718_2599_60sec.mp3
                )

            [type] => Array
                (
                    [0] => audio/mpeg
                )

            [tmp_name] => Array
                (
                    [0] => /tmp/phpf4TEtW
                )

            [error] => Array
                (
                    [0] => 0
                )

            [size] => Array
                (
                    [0] => 724575
                )

        )

    [mp2] => Array
        (
            [name] => Array
                (
                    [0] => 782718_2599_60sec.mp3
                )

            [type] => Array
                (
                    [0] => audio/mpeg
                )

            [tmp_name] => Array
                (
                    [0] => /tmp/phpI56ATf
                )

            [error] => Array
                (
                    [0] => 0
                )

            [size] => Array
                (
                    [0] => 724575
                )

        )

    [mp3] => Array
        (
            [name] => Array
                (
                    [0] => 782718_2599_60sec.mp3
                )

            [type] => Array
                (
                    [0] => audio/mpeg
                )

            [tmp_name] => Array
                (
                    [0] => /tmp/phplyKobX
                )

            [error] => Array
                (
                    [0] => 0
                )

            [size] => Array
                (
                    [0] => 724575
                )

        )

)

 

But theres only one uploaded ... weird ...

 

This is the full PHP code as it is right now

echo '<pre>$_POST:' . print_r($_POST,true) . '</pre>';
echo '<pre>$_FILES:' . print_r($_FILES,true) . '</pre>';		  
	  
$i=0;
foreach ($_POST[i] as $value){

// Debug line
//echo "We are taking care of $nb loops";

$file_name = $_FILES['mp3']['name'][$i];
$file_tmp = $_FILES['mp3']['tmp_name'][$i];

echo "<br><br><b>This is loop $i</b><br>"; 
echo "<b>The name of the file is $file_name</b><br>";	
echo "<b>The var is mp3_$i</b><br><br>";
  
//Ici je regarde si l'extantion du code est autoriser
$ext = strrchr($_FILES['mp3']['name'][$i],'.');
if (($extlimit == "OUI") && (!in_array($ext,$limitedext))) {
echo "Le MP3 num $i n'a pas un extension autoriser. (mp3 seulement)<br>";
}else{

// Ici je regarde si le fichier existe déjà.
if(file_exists($upload_dir.$_FILES['mp3']['name'][$i])){
$random_digit=rand(0000,9999)."_";
}else{unset($random_digit);}

if (move_uploaded_file($file_tmp,$_SERVER['DOCUMENT_ROOT']."/admin/site/".$upload_dir.$random_digit.$_FILES['mp3']['name'][$i])){

chmod($_SERVER['DOCUMENT_ROOT']."/admin/site/".$upload_dir.$random_digit.$_FILES['mp3']['name'][$i], 0755);   
$mp3 = new mp3($upload_dir.$random_digit.$_FILES['mp3']['name'][$i]);
$mp3_1 = $mp3->extract(0,30);
$newname=rand("100000", "999999")."_";
$mp3_1->save($upload_demo_dir.$newname.$random_digit.$_FILES['mp3']['name'][$i]);

$insert=mysql_query("INSERT INTO `distadp_adpsite`.`artiste_mp3` (id, nom_mp3, nom_demo, num_albume, nom)VALUES (NULL , '".$random_digit.$_FILES['mp3']['name'][$i]."', '".$newname.$random_digit.$_FILES['mp3']['name'][$i]."', '$_GET[id]', '".$_POST['nom'][$i]."')");

echo "<br>MP3 numéro $i uploadé! (<a href='http://distributionadp.info/admin/site/$upload_dir$random_digit".$_FILES['mp3']['name'][$i]."'>".$_FILES['mp3']['name'][$i]."</a>)<br>";
echo "Démo de 30 sec créé avec succès! (<a href='http://distributionadp.info/admin/site/$upload_demo_dir$newname$random_digit".$_FILES['mp3']['name'][$i]."'>$newname".$_FILES['mp3']['name'][$i]."</a>)<br><br>";

}else{
echo "Il ya eu une éreure inconnu dans le transfère du fichier du mp3 num $i (".$_FILES['mp3']['name'][$i].")<br>";
}
}
$i++;
}

 

only the first one is uploaded

Link to comment
https://forums.phpfreaks.com/topic/105653-foreach-loop-prob/#findComment-541337
Share on other sites

I took your code with the javascript, took out some lines and got this:

<?php
if (isset($_POST['submit'])) {
echo '<pre>' . print_r($_POST,true) . print_r($_FILES,true) . '</pre>';
$i=0;
foreach ($_POST['i'] as $value){

// Debug line
//echo "We are taking care of $nb loops";

$file_name = $_FILES['mp3']['name'][$i];
$file_tmp = $_FILES['mp3']['tmp_name'][$i];

echo "<br><br><b>This is loop $i</b><br>"; 
echo "<b>The name of the file is $file_name</b><br>";
echo "<b>The var is mp3_$i</b><br><br>";
$i++;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>
<head>
<title></title>
<script type="text/javascript">
var fields;

function HTMLBlock(el) {
var instance = 1, elementNames = [], i, item, container;

/* remove source element */
container = el.parentNode;
container.removeChild(el);

/* cache input elements' name attributes */
for (i = 0; item =
el.getElementsByTagName("input").item(i); i++) {
elementNames[i] = item.getAttributeNode("name");
}

/* method to modify and insert a clone of the original element */
this.insert = function () {
for (var i = elementNames.length; i--; ) {
/* replace digits with instance # */
elementNames[i].nodeValue =
elementNames[i].nodeValue.replace(/d+/, instance);
}
instance++;
container.appendChild(el.cloneNode(true));
};
}

function createHTMLBlock(id) {
var d = document, el;

/* test browser supports the methods we'll be using */
if (d.getElementById && (el = d.getElementById(id)) &&
el.getElementsByTagName && el.cloneNode &&
el.getAttributeNode) {
/* ... etc. */
return new HTMLBlock(el); // yes
}
return null; // no
}

function addHTML() {
if (fields) {
fields.insert();
}
}
</script>
</head>

<body>
<form action="" method="post" enctype="multipart/form-data">
<center><input type="button" onclick="addHTML()" value="Add Fields"></center><br>

<div id="new_link_fields"><div id="form_source"><span class="r">Nom: <input type='text' name='nom[]' value='' size='20'><input type='hidden' name='i[]' value='1'> <input type='file' name='mp3[]' size='30'><br></span></div></div>

<script type="text/javascript">
/* remove the HTML and set up the object down here, before
anything's displayed */
fields = createHTMLBlock("form_source");
</script>
<input type="submit" name="submit" value="Upload">
</form>


</body>
</html>

 

It works fine in my tests. Check my code against your code.

 

If you want to see my code in actions go to http://www.rbnsn.com/phpfreaks/mp3-1.php

 

 

Ken

Link to comment
https://forums.phpfreaks.com/topic/105653-foreach-loop-prob/#findComment-541466
Share on other sites

i think you set wrong upload file name.

 

<form action="" method="POST" enctype="multipart/form-data">
<div id="new_link_fields0">
   <div id="form_source0">
     <span class="r">Nom: <input name="nom_0"><input type="hidden" value="1" name="i[]">
     <input type="file" size="30" name="mp3_0"><br> </span>
  </div>
  <div id="form_source1">
     <span class="r">Nom: <input name="nom_1"><input type="hidden" value="1" name="i[]">
     <input type="file" size="30" name="mp3_1"><br> </span>
  </div>
  <div id="form_source2">
     <span class="r">Nom: <input name="nom_2"><input type="hidden" value="1" name="i[]">
     <input type="file" size="30" name="mp3_2"><br> </span>
  </div>
  <div id="form_source3">
     <span class="r">Nom: <input name="nom_3"><input type="hidden" value="1" name="i[]">
     <input type="file" size="30" name="mp3_3"><br> </span>
  </div>
  <div id="form_source4">
     <span class="r">Nom: <input name="nom_4"><input type="hidden" value="1" name="i[]">
    <input type="file" size="30" name="mp3_4"><br> </span>
  </div>
  <div><input type="submit" name="submit" value="submit" />
</div>
</form>

 

Change php code for uploading

 


   if($_POST)
   {
foreach ($_POST[i] as $key=>$value)
{

  $file_name = $_FILES['mp3_' . $key]['name'];
  $file_tmp = $_FILES['mp3_' . $key]['tmp_name'];

  if ($file_name && $file_tmp)
  {
	echo '<p>The file ' . $file_name . ' is number ' . $key . '</p>';
  }
}
   }

Link to comment
https://forums.phpfreaks.com/topic/105653-foreach-loop-prob/#findComment-541485
Share on other sites

Archived

This topic is now archived and is closed to further replies.

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