插入后获取自动增量ID以在另一个插入上使用

时间:2015-03-24 14:02:28

标签: php mysql

我正在使用插入查询将PHP表单中的信息添加到表中以及上传图像。表单信息和图像目录路径将存储在单独的表中。这是我正在做的事情,但它似乎没有用。

//insert data from my form into DB, id is auto incremented so it's not in the insert.
$query = "INSERT INTO infotable (number, name, address, city, province, postal_code VALUES ('$facilityNumber', '$facilityName', '$facilityAddress', '$facilityCity', '$facilityProvince', '$facilityPostalCode' )";
mysqli_query($dbc, $query);

//query used to get the id of the facility we had just entered
$getFacilityID = "SELECT id FROM infotable WHERE number = '$facilityNumber' AND name = '$facilityName' "
    . "AND address = '$facilityAddress' AND city = '$facilityCity'";

$queryData = mysqli_query($dbc, $getFacilityID);
$row = mysqli_fetch_assoc($queryData);

//attempt to echo out the value of the ID (this is always empty)
echo $row['id'];

//insert image into image table + id from infotable ... I haven't even got to test this yet.
$imageQuery = "INSERT INTO photo (id, photo, photo_desc)"
            . "VALUES ($row['id'], $facilityPhoto, $facilityPhotoDesc)";

mysqli_query($dbc, $imageQuery);

2 个答案:

答案 0 :(得分:1)

您需要mysqli_insert_id来解决您的问题。

参见程序示例: http://www.w3schools.com/php/php_mysql_insert_lastid.asp

答案 1 :(得分:1)

要获取自动增量ID,只需使用内置的mysqli_insert_id函数:

$getFacilityID = mysqli_insert_id($dbc);

然后可以重写您的代码,如下所示:

//insert data from my form into DB, id is auto incremented so it's not in the insert.
$query = "INSERT INTO infotable (number, name, address, city, province, postal_code VALUES ('$facilityNumber', '$facilityName', '$facilityAddress', '$facilityCity', '$facilityProvince', '$facilityPostalCode' )";
mysqli_query($dbc, $query);

//query used to get the id of the facility we had just entered
$getFacilityID = mysqli_insert_id($dbc);

//attempt to echo out the value of the ID (this is always empty)
echo $getFacilityID;

//insert image into image table + id from infotable ... I haven't even got to test this yet.
$imageQuery = "INSERT INTO photo (id, photo, photo_desc)"
        . "VALUES ($getFacilityID, $facilityPhoto, $facilityPhotoDesc)";

mysqli_query($dbc, $imageQuery);
相关问题