简体   繁体   中英

Two arrays in foreach loop?

having difficulties because of my noobness, again. I dont know if I am doing this right, but I need to post an id variable with an array through a foreach loop to a mysql db. If that made no sense, its probably due to my lack of ability to articulate with technical jargon, so ill just post the code. Please view the notes in the PHP code.

Any help always appreciated.

Cheers, Lea

FORM:

<form method="post" action="<?php echo $PHP_SELF; ?>" enctype="multipart/form-data">

 <?php
    $num = 0;
    while($num < $num_uploads)
    {
        ?>
<input type="hidden" name="item_id[]" value="<?php echo $stockno; ?>" />
<input type="file" id="myfile" name="userfile[]" size="40">

        <?php $num++;
    }
 ?>
<input type="submit" name="Preview" value="Preview" />
</form>

PHP SCRIPT:

if(isset($_POST['Preview']) ) {
// START PHOTO QUERY

    if(isset($_FILES['userfile']['tmp_name']))
    {
        /** loop through the array of files ***/
        for($i=0; $i < count($_FILES['userfile']['tmp_name']);$i++)
        {
            // check if there is a file in the array
            if(!is_uploaded_file($_FILES['userfile']['tmp_name'][$i]))
            {
                $messages[] = 'No file uploaded';
            }
            /*** check if the file is less then the max php.ini size ***/
            elseif($_FILES['userfile']['size'][$i] > $upload_max)
            {
                $messages[] = "File size exceeds $upload_max php.ini limit";
            }
            // check the file is less than the maximum file size
            elseif($_FILES['userfile']['size'][$i] > $max_file_size)
            {
                $messages[] = "File size exceeds $max_file_size limit";
            }
            else
            {
                // copy the file to the specified dir 
                if(@copy($_FILES['userfile']['tmp_name'][$i],$upload_dir.'/'.$_FILES['userfile']['name'][$i]))
                {
                    /*** give praise and thanks to the php gods ***/
                    $messages[] = $_FILES['userfile']['name'][$i].' uploaded';
                    $name[] = $_FILES['userfile']['name'][$i];
                    $id[] = $_POST['item_id'];

// HAVING DIFFICULTIES HERE

foreach( $name as $value ) {
$sql = "INSERT INTO stock_photos (photo_filename) VALUES ('$value')";
mysql_query($sql);
foreach( $id as $val ) {
$sql2 = "UPDATE stock_photos SET photo_item_id = '$val' WHERE photo_filename = '$value'";
mysql_query($sql2) or die(mysql_error());
}
}
// END DIFFICULTIES HERE
                }
                else
                {
                    /*** an error message ***/
                    $messages[] = 'Uploading '.$_FILES['userfile']['name'][$i].' Failed';
                }
            }
        }
    }

// END PHOTO QUERY
}

I think you have a flaw in your logic. You don't want to have a nested foreach loop. Think about it:

You are looping over each filename. For each filename, you are looping over all IDs and update the filename ID with with each value from the ID array. You are basically overwriting the ID in the database with every UPDATE call, eventually setting the value to the last value of the $id array.

Thus, you actually should have the loops one after each other.


Assuming your $name and $id are filled properly and both contain the same number of items, you can do even better, using a normal for loop:

for($i = 0; $i < count($name); $i++ ) {
    $sql = "INSERT INTO stock_photos (photo_filename, photo_item_id) VALUES ('".   mysql_real_escape_string($name[$i]) . "', '" . mysql_real_escape_string($id[$i] . "')";
    mysql_query($sql);
}

Note: Never never never trust user input, so take precautions through filtering and escaping like I did with mysql_real_escape_string() .


Update:

And you can do even better with just one MySQL query by inserting multiple values at once:

function prepare($name, $id) {
    return sprintf("'%s', '%s'",
           mysql_real_escape_string($name),
           mysql_real_escape_string($id));
}

$values = array_map('prepare', $name, $id); 
$sql = 'INSERT INTO stock_photos (photo_filename, photo_item_id) VALUES (' . implode('),(', $values) . ')';  
mysql_query($sql);

Reference: sprintf , array_map , implode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM