0

I am trying to insert data from an array in mysql. I have multiple arrays. I have been trying to do something along the lines of this.

foreach ($titles as $title && $descriptions as $description) {
    mysql_query("INSERT INTO `stock` VALUES('', '$title', '$description')");
}

I would like mysql table to look like this.

item_id    title    description
_______________________________

1          title1   description1
2          title2   description2
...

Now I have figured out this won't work is there any alternative to this. I have seen examples of while loops to do this but i am struggling to understand how that would work. All help is appreciated in advance.

2 Answers 2

3

if size of $titles equal size of $descriptions and, you have sequencial arrays, you can do:

<?php
$titles = array(
    'foo',
    'bar'
);
$descriptions = array(
    'foo description',
    'bar description'
);

for($i = 0; $i < count($titles); $i++) {
    $title = $titles[$i];
    $description = $descriptions[$i];

    mysql_query("INSERT INTO `stock` VALUES('', '$title', '$description')");
}
Sign up to request clarification or add additional context in comments.

Comments

3

You're looking for a MultipleIterator, which will iterate over both arrays easily:

$iter = new MultipleIterator;
$iter->attachIterator( new ArrayIterator( $titles));
$iter->attachIterator( new ArrayIterator( $descriptions));

foreach( $iter as $data) {
    list( $title, $description) = $data;
    // Do your SQL insert with $title and $description
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.