Jump to content

Transactions problem: Inserting data into two tables.


leke

Recommended Posts

Hi, I'm trying to insert data into two different tables using, but am getting an error I can't figure out. If I move the $mysqli->commit(); into the foreach loop, I get at least one returned row before the rest fail. The error current error message is Array ( [0] => Error: Couldn't insert into english! ). Any idea what is causing this?

<?php 

$file_array = file('../grammar/conjunctions.txt');
$csv = array_map('str_getcsv', $file_array);

// DB
$mysqli = new mysqli('localhost', 'root', '******', 'angos');

$mysqli->autocommit(false);
$error = array();

foreach($csv as $value)
{
    $angos_query = $mysqli->query("INSERT INTO angos (angos, grammar) VALUES ('$value[0]', 'con')");
    $id = $mysqli->insert_id; // grab the currant angos table id
    if($angos_query == false)
    {
        array_push($error, "Error: Couldn't insert into angos!");
    }
    
    $english_query = $mysqli->query("INSERT INTO english (angos_id, english) VALUES ('$id', '$value[1]')");
    if($english_query == false)
    {
        array_push($error, "Error: Couldn't insert into english!");
    }
    
    if(!empty($error))
    {   
        $mysqli->rollback();
    }
    
}

$mysqli->commit();

print_r($error);
// print_r($csv);

?> 

More info SQL:

CREATE TABLE angos 
	(
        id int unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, 
        angos varchar(255) not null, 
        grammar varchar(3) not null, 
        updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        CONSTRAINT unique_input UNIQUE (angos)
    ) engine=InnoDB;

CREATE TABLE english 
	(
        id int unsigned not null primary key,
        angos_id int unsigned,
        english varchar(255),
        grammar_note varchar(500),
        CONSTRAINT fk_angos_source FOREIGN KEY (angos_id) REFERENCES angos(id) ON DELETE CASCADE ON UPDATE CASCADE
    ) engine=InnoDB;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.