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 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示