Jump to content

Transactions problem: Inserting data into two tables.


leke
Go to solution Solved by 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;
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.