douban2014 2014-03-14 18:11
浏览 30
已采纳

在PDO语句中为2个MySQL表行分配相同的id

I am having trouble wrapping my brain around how I would do this. I just started learning about about PDO, so forgive the ignorance. I have a form that simply inserts some post data and image data into a MySQL database. I have a separate table for post data and image data. They both have a row called postid. The posts postid currently is set to AUTO_INCREMENT I just simply need to have the same postid go into both images and posts tables. However, it is not quite that simple. An image will not always be added to every post. So simply having AUTO_INCREMENT on both to increment simultaneously would not suffice. The images postid just needs to always match the corresponding posts postid

I know this isn't a very specific question regarding a code issue, but was hoping i could get some good insight at least.

This is the code I currently have functioning correctly aside from adding postid to the images table.

<!DOCTYPE html>
<html>
<body>
<center>
  <form enctype="multipart/form-data" action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="99999999" />
    <div><textarea name="entry" maxlength="600"></textarea></div>
    <div><input name="userfile" type="file" /></div>
    <div><input type="submit" value="Submit" /></div>
  </form>

</body></html>


<?php
/*** check if a file was submitted ***/
if(!isset($_FILES['userfile']))
    {
    echo '<p>Please select a file</p>';
    }
else
    {
    try    {
        upload();
        /*** give praise and thanks to the php gods ***/
        echo '<p>Thank you for submitting</p>';
        }
    catch(Exception $e)
        {
        echo '<h4>'.$e->getMessage().'</h4>';
        }
    }
?>

<?php
//Upload function
function upload(){

/*** check if a file was uploaded ***/
if(is_uploaded_file($_FILES['userfile']['tmp_name']) && getimagesize($_FILES['userfile']['tmp_name']) != false)
    {
    /***  get the image info. ***/
    $size = getimagesize($_FILES['userfile']['tmp_name']);
    /*** assign our variables ***/
    $type = $size['mime'];
    $imgfp = fopen($_FILES['userfile']['tmp_name'], 'rb');
    $size = $size[3];
    $name = $_FILES['userfile']['name'];
    $maxsize = 99999999;
    $poster = $_SESSION['username'];
    $entry = $_POST['entry'];


    /***  check the file is less than the maximum file size ***/
    if($_FILES['userfile']['size'] < $maxsize )
        {
        /*** connect to db ***/
        $dbh = new PDO("mysql:host=localhost;dbname=db_name", 'user', 'password');

                /*** set the error mode ***/
                $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            /***sql query ***/
        $stmt = $dbh->prepare("INSERT INTO images (image_type ,image, image_size, image_name) VALUES (? ,?, ?, ?)");
        $stmt2 = $dbh->prepare("INSERT INTO posts (poster, entry) VALUES (? ,?)");

        /*** bind the params ***/
        $stmt->bindParam(1, $type);
        $stmt->bindParam(2, $imgfp, PDO::PARAM_LOB);
        $stmt->bindParam(3, $size);
        $stmt->bindParam(4, $name);
        $stmt2->bindParam(1, $poster);
        $stmt2->bindParam(2, $entry);

        /*** execute the query ***/
        $stmt->execute();
        $stmt2->execute();

        }
    else
        {
        /*** throw an exception is image is not of type ***/
        throw new Exception("File Size Error");
        }
    }
else
    {
    // if the file is not less than the maximum allowed, print an error
    throw new Exception("Unsupported Image Format and/or to large of a file.");
    }
}
?>
  • 写回答

3条回答 默认 最新

  • duanlan4801 2014-03-14 18:14
    关注
    1. Execute the query that inserts the post, which creates the auto increment id.
    2. Use $dbh->lastInsertId() to get this new id.
    3. Prepare the image query and use the id you got in step 2.
    $stmt = $dbh->prepare("INSERT INTO posts (poster, entry) VALUES (?, ?)");
    ...
    $stmt->execute();
    $id = $dbh->lastInsertId();
    
    $stmt = $dbh->prepare("INSERT INTO images (post_id, image_type, image, image_size, image_name) VALUES (?, ? ,?, ?, ?)");
    $stmt->bindParam(1, $id);
    ...
    $stmt->execute();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB代码补全插值
  • ¥15 Typegoose 中如何使用 arrayFilters 筛选并更新深度嵌套的子文档数组信息
  • ¥15 前后端分离的学习疑问?
  • ¥15 stata实证代码答疑
  • ¥50 husky+jaco2实现在gazebo与rviz中联合仿真
  • ¥15 dpabi预处理报错:Error using y_ExtractROISignal (line 251)
  • ¥15 在虚拟机中配置flume,无法将slave1节点的文件采集到master节点中
  • ¥15 husky+kinova jaco2 仿真
  • ¥15 zigbee终端设备入网失败
  • ¥15 金融监管系统怎么对7+4机构进行监管的