1

I need to save data from this array to MySQL database

0 => {#517 ▼
    +"id": 59
    +"name": "example_name_1"
    +"category": "category_1"
    +"price": 100
    +"description": "example_description_1"
}
1 => {#516 ▼
    +"id": 60
    +"name": "example_name_2"
    +"category": "category_2"
    +"price": 200
    +"description": "example_description_2"
}

I am tryinig to save like this, but reveive errors like

Undefined index: name

for ($idx = 0; $idx < count($products); $idx++)
{
    $values = new Product();
    $values->name = $products["name"][$idx];
    $values->category= $products["category"][$idx];
    $values->description = $products['description'][$idx];
    $values->price = $products['price'][$idx];
    $values->save();
}
2
  • 1
    Dump the variable products to understand how to use it. You have to use a foreach ($products as $product) { $product->name ... } Commented Aug 13, 2017 at 21:16
  • thanks, it works now. Commented Aug 13, 2017 at 21:27

1 Answer 1

4

You get that error because the order you accessed the array is incorrect.

The order should be the which product index and then name, category or whichever field.

for ($idx = 0; $idx < count($products); $idx++)
{
    $values = new Product();
    $values->name = $products[$idx]["name"];
    $values->category= $products[$idx]["category"];
    $values->description = $products[$idx]['description'];
    $values->price = $products[$idx]['price'];
    $values->save();
}

Or you can easily use a foreach as @VincentDecaux mentioned in his comment.

foreach ($products as $product) {
    $values = new Product();
    $values->name = $product["name"];
    $values->category= $product["category"];
    $values->description = $product['description'];
    $values->price = $product['price'];
    $values->save();
}
Sign up to request clarification or add additional context in comments.

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.