doujiao3072 2015-03-24 14:02
浏览 26
已采纳

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

I am using an insert query to add information from a PHP form into a table as well as upload an image. The form information and the image directory path are to be stored in separate tables. Here is what I am doing but it just does not seem to work.

//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条回答 默认 最新

  • donglin8467 2015-03-24 14:08
    关注

    To get the auto-increment id, just use the built-in mysqli_insert_id function:

    $getFacilityID = mysqli_insert_id($dbc);
    

    Your code could then be re-written as below:

    //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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘