【问题标题】:How to retrieve ImageId from one db table and store it in another db table如何从一个数据库表中检索 ImageId 并将其存储在另一个数据库表中
【发布时间】:2012-06-11 01:36:12
【问题描述】:

我有一个 INSERT 函数,它在“Image”表的“ImageFile”字段中插入图像文件名,由于自动编号,每一行都有自己的 ImageId。下面是一个例子:

ImageId    ImageFile

23         orange.jpg
24         flowers.png
25         castle.png
26         orange.jpg

我还想做的是将 ImageId 插入另一个带有 QuestionId 和 SessionId 的表中,以便该表(Image_Question)可以使用 ImageId 将 Image 表与 Image Question 表链接。现在我正在尝试使用 mysql_insert_id 从 Image 表中检索 ImageId 并将其存储在 Image_Question 表中的 ImageId 中。

但我似乎无法弄清楚我需要做什么,目前图像表中的 INSERTING 值工作正常,但它没有在 Image_Question 表中插入任何值。

所以我的问题是对于插入到 Image 表中的每一行,如何从 Image 表中检索 ImageId,并使用 mysql_insert_id() 将其插入到 Image_Question 表中? 示例如下:

ImageId   SessionId  QuestionId

23        AAA        1
24        AAA        2
25        AAA        3
26        AAA        4

我已经编写了 SessionId 和 QuestionId 的 INSERT 值,但只需要帮助来检索和插入 ImageId。以下是当前代码:

<?php

session_start();


//connect to db

$result = 0;
$i = 0;
$insertimage = array();
$lastimageid = mysql_insert_id();


      move_uploaded_file($_FILES["fileImage"]["tmp_name"],
      "ImageFiles/" . $_FILES["fileImage"]["name"]);
      $result = 1;

        $imagesql = "INSERT INTO Image (ImageFile) 
        VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";

    for($i = 0;  $i < $c; $i++ ){


    $insertimage[] = "'". mysql_real_escape_string( $lastimageid [$i] ) ."','". 
                    mysql_real_escape_string($_SESSION['id'] ) . 
                    ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '') ."' ,'". 
                    mysql_real_escape_string( $_POST['numQuestion'][$i] ) ."'";

}

    $imageinsertsql = "INSERT INTO Image_Question (ImageId, SessionId, QuestionId) 
    VALUES (" . implode('), (', $insertimage) . ")";

    mysql_query($imageinsertsql);

    mysql_query($imagesql);

      }

      mysql_close();

?>

我有一个旧的 php 版本 5.2.13,因为那是大学服务器的版本。

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    你需要运行

    $lastimageid = mysql_insert_id();
    

    将其插入数据库后。

    【讨论】:

      【解决方案2】:

      您需要重新排序您的 php 代码才能运行

      mysql_query($imagesql); 
      $lastimageid = mysql_insert_id(); 
      mysql_query($imageinsertsql);
      

      当前您检索 lastimageid,插入 Image_Question 然后插入 Image。

      【讨论】:

        猜你喜欢
        • 2012-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-31
        相关资源
        最近更新 更多