SQL PHP如何根据另一个表的主键更新外键?

时间:2016-04-12 02:23:54

标签: php sql key match

我环顾四周并尝试了解决方案,但由于某种原因,这不起作用。我有一个tables_albums表,其中albums_id是主要的,自动递增键。在我的coming_albums_tracks表中,每当我创建新专辑时,我都希望其albums_id更新为与albums_id中的值相同。

这是我的php类文件中的方法

public function create ($title, $content, $date, $price){ 

$db = Dbclass::getDB();
$query = "INSERT INTO upcoming_albums (albums_title, albums_content, albums_date, albums_price, albums_img_path)
            VALUES (:title, :content, :date, :price, :path)";

$statement = $db->prepare($query);
$statement->bindParam(':title', $title, PDO::PARAM_STR, 50);
$statement->bindParam(':content', $content);
$statement->bindParam(':date', $date);
$statement->bindParam(':price', $price, PDO::PARAM_STR, 10);
$statement->bindValue(':path', $this->target_path, PDO::PARAM_STR);

$statement->execute();

$query = "UPDATE upcoming_albums_tracks
            SET albums_id = upcoming_albums.albums_id
            FROM upcoming_albums_tracks
            WHERE upcoming_albums_tracks.albums_title = upcoming_albums.albums_title";

$statement = $db->prepare($query);

$statement->execute();   

}

创建相册效果很好,但coming_albums_tracks表的albums_id不会从NULL变为它应该的值。

这是一个问题的视觉效果。

coming_albums表:

enter image description here

coming_albums_tracks表(我需要albums_id是相同的,不是NULL)

enter image description here

UPDATE 这是我处理插入曲目的方法。请注意,每个专辑都有多个轨道,因此首先调用我的create方法,然后插入foreach轨道,我运行以下方法。现在的问题是什么都没有插入:

public function createTrack ($title, $track, $index) {

        $db = Dbclass::getDB();
        $lastInsertId = $db->lastInsertId();    

        $query = "INSERT INTO upcoming_albums_tracks (albums_id, albums_title, albums_track, albums_track_path, albums_track_file)
                    VALUES (" . $lastInsertId . " :title, :track, :path, :file_name)";

        $statement = $db->prepare($query);
        $statement->bindParam(':title', $title, PDO::PARAM_STR, 50);
        $statement->bindParam(':track', $track, PDO::PARAM_STR, 50);
        $statement->bindValue(':path', $this->tracks[$index]['target_path'], PDO::PARAM_STR);
        $statement->bindValue(':file_name', $this->tracks[$index]['file_name'], PDO::PARAM_STR);

        $statement->execute();

    }

奇怪的是,如果我尝试回显$ lastInsertId,它会给我正确的数字。

2 个答案:

答案 0 :(得分:1)

您需要的是获取插入的最后一条记录的ID。要在MySQL中实现这一点,您可以使用:

 $last_id = mysqli_insert_id($conn);

看看这个enter link description here

答案 1 :(得分:1)

试试这个

$lastInsertId = $db->lastInsertId();

$query = "UPDATE upcoming_albums_tracks SET albums_id = $lastInsertId FROM upcoming_albums_tracks WHERE upcoming_albums_tracks.albums_title = upcoming_albums.albums_title";
相关问题