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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度