How to insert an array of unknown size within the database?

Asked

Viewed 18 times

-1

I’m trying to insert into the database several rows of data that comes from an array. I’ve never done anything like this, because I always insert one line at a time. I wonder what I’m doing wrong?

inserir a descrição da imagem aqui inserir a descrição da imagem aqui inserir a descrição da imagem aqui inserir a descrição da imagem aqui

  • Friend, I see you are using the Mysql extension INSERT INTO 'table' SET ..., for multiple values you need to use the standard SQL notation that is INSERT INTO 'table' ('col1', 'col2', 'col3') VALUES ('row1val1', 'row1val2', 'row1val3'), ('row2val1', ...) ...

  • Tiago, I suggest that you never put your code as an image, the training rule is to put it in blocks of code, facilitates understanding and that your question be answered. In its present form it can even be removed by moderation.

1 answer

0


Supposing $this->db be your Mysqli connection

public function addItemCaja($teste) {
    $stmt = $this->db->prepare("INSERT INTO item_juego (id_caja, id_item, cantidad) VALUES (?, ?, ?)");

    foreach($teste as $item){
        $stmt->bind_param('i', $item['id_caja']); //supondo que id_caja é integer
        $stmt->bind_param('i', $item['id_item']); //supondo que id_caja é integer
        $stmt->bind_param('i', $item['cantidad']); //supondo que id_caja é integer

        $stmt->execute();
    }

    $stmt->close();
}

Doing this way you also avoid problems with SQL Injection.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.