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

-1

I'm trying to insert multiple rows with data coming from an array into the database. I've never done anything like that, since I always insert one line at a time. What am I doing wrong?

    
asked by anonymous 09.06.2018 / 16:45

1 answer

0

Assuming $this->db is your MySQL 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 also avoids problems with SQL Injection.

    
09.06.2018 / 17:10