StudioTime
StudioTime

Reputation: 23969

Multiple values added to the same record - MySQL PHP

I have a table, itemColors:

itemID INT(11)
color1 VARCHAR(7)
color2 VARCHAR(7)
color3 VARCHAR(7)
color4 VARCHAR(7)
color5 VARCHAR(7)

I have data instances where I need to add up to 5 values to an item. But the item will not exist until I create it. I say up to because it's just that.

e.g.

item1
value1=1
value2=2

item2
value1=10
value2=20
value3=30
value4=40
value5=50

The values come from an array so i'm presuming

foreach ($array as $value){
    // add $value here
}

I'm not sure how to deal with different array lengths input into the same item. Ideas welcome. What's the most efficient way to do this?

Upvotes: 0

Views: 36

Answers (2)

Ali MasudianPour
Ali MasudianPour

Reputation: 14459

If I get what you want correctly, First you can check the array size by using count(array()) in order to prevent more than 5 values. But for different values, just use a for loop instead of foreach:

    for ($i = 1; $i < count($YOUR_ARRAY); $i++) {
        $value.$i=$YOUR_ARRAY[$i]; // value1=your array value - value2=array value and so on...
    }

Then, You are able to do any manipulations with your values.

Upvotes: 1

Yubraj Pokharel
Yubraj Pokharel

Reputation: 485

lets assume your array is

    $array_name = array( 'blue' , 'red' , 'green', 'black' , 'white');

    foreach($yourArr as $name => $color) {
      //your insert query here
      $color = mysql_real_escape_string($color);
      $sql = "INSERT INTO TABLE_NAME VALUES ('$array_name')";
      $query = mysql_query($sql);
   }

Upvotes: 0

Related Questions