如何获得自动递增的ID

时间:2017-03-21 05:39:39

标签: php mysqli

我正在尝试为photo_idalbum_id获取自动增加的ID,但mysql_insert_id()会返回NULL,即使照片已成功插入到相册和照片表中。要注意,Albums(album_id,...)和Photos(photo_id,...)表中的ID会自动递增,但PhotosInAlbums(album_id,photo_id)中的ID不会。

global $mysqli;
$album_title = $_POST['title'];
$credit = $_POST['credit'];

//Insert album into albums table
mysqli_query($mysqli,"INSERT INTO Albums (`title`, `date_created`, `date_modified`, `album_image`)
                        VALUES ('$album_title', NOW(), NOW(), 'images/$originalName')") 
                        or die(mysqli_error($mysqli));

$album_id = mysqli_insert_id(); //gets id of previous query

//Insert album image into photos table
mysqli_query($mysqli,"INSERT INTO Photos (`title`, `date_created`, `date_modified`, `file_path`, `credit`)
                        VALUES ('$album_title', NOW(), NOW(), 'images/$originalName', '$credit')") 
                        or die(mysqli_error($mysqli));

$photo_id = mysqli_insert_id();


//Insert album_id and photo_id into photosInAlbums table
mysqli_query($mysqli,"INSERT INTO PhotosInAlbums (`album_id`, `photo_id`)
                        VALUES ('$album_id', '$photo_id')") 
                        or die(mysqli_error($mysqli));

为表创建代码

CREATE TABLE Albums
(
     album_id int(6) NOT NULL AUTO INCREMENT,
     title varchar(150) NOT NULL,
    date_created datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
    date_modified datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
    album_image varchar(150),
    PRIMARY KEY(album_id)
);
 
    CREATE TABLE Photos
    (
    photos_id int(6) NOT NULL AUTO INCREMENT,
      title varchar(150) NOT NULL,
        date_created datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
        date_modified datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
        file_path varchar(150) NOT NULL,
    credit varchar(150) NOT NULL,
        PRIMARY KEY(photos_id)
);

0 个答案:

没有答案