I have the following database-model:
This database gets filled by loading in a CSV file. Let's say this is the CSV file:
This is how the CSV gets loaded into the database: First I take all the values of foo_name
and insert them into the table Foo
. I only fill name. ID is autoincrement. The same happens for bar_name
. Note that all names
can only exist one time in the table. So even when Jefferson
appears twice in the CSV, it exists only one time in the actual database table. Same for Foo
. strong text
That works perfectly. The tables get filled. But as you can see, the table Foo
holds a foreign key to Bar
.
I want to put Bar(ID)
into Foo(bar_id)
where Foo(name)
and Bar(name)
are in the same row in the CSV file.
I tried to do it by looping over the CSV file again. For every Foo(name)
I retrieve Foo(ID)
. I also retrieve Bar(ID)
. Then I update Foo(bar_id)
with the ID
in Bar
that matches Bar(name)
.
This is the code in my while-loop for reading the csv:
$foo = $column[0];
$bar = $column[1];
$foo_id = 0;
$stmt = $conn->prepare("SELECT ID from Foo WHERE name=?");
$stmt->bind_param("s", $name_);
$name_ = $foo;
$stmt->execute();
$stmt->bind_result($id);
$stmt->fetch();
$foo_id = $id;
$stmt->close();
$bar_id = 0;
$stmt = $conn->prepare("SELECT ID from bars WHERE name=?");
$stmt->bind_param("s", $name_);
$name_ = $bar;
$stmt->execute();
$stmt->bind_result($id);
$stmt->fetch();
$bar_id = $id;
$stmt->close();
//echo $foo_id . " - " . $bar_id . "<br>";
$stmt = $conn->prepare("UPDATE foo SET bar_id=? WHERE ID=?");
if (!$stmt) {
die("Statement failed (" . $stmt->errno . "): " . $conn->error);
}
$stmt->bind_param("ii", $bar_, $id_);
$bar_ = $bar_id;
$id_ = $foo_id;
if(!$stmt->execute()) {
echo $stmt->error;
}
echo $stmt->affected_rows . "<br>";
$stmt->close();
This line echo $foo_id. " - ". $bar_id. "<br>";
echo $foo_id. " - ". $bar_id. "<br>";
nicely outputs foo_id
and bar_id
like it should. $stmt->affected_rows
does return 1
almost each time. So something should be updated. I got no errors at all. And doing UPDATE foo SET bar_id=? WHERE ID=?
UPDATE foo SET bar_id=? WHERE ID=?
manually in the database works.
Despite this all, the column bar_id
is not updated/saved.
The code above is working. I made some other stupid mistake. While reading the CSV-file for the first time to fill the tables, the values first get written to an array.
Then I read it another time to set the relations.
The problem is that I wrote from memory to database at the very end of my code. Resulting in overwriting the column-values holding the relation. Solved.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.