如何通过php将图像从一个表保存到另一个表?

时间:2018-06-17 18:23:21

标签: php database image mysqli

我的数据库中有两个单独的表。一个用于原始图像,另一个用于标记图像。我希望它表现得像这样:

  1. 使用以下查询从前端的第一个数据库获取随机图像:
  2.  <form
      <div class="col-4 col-12-small">
                            <input type="radio" id="radio-Fear" name="radio" value="7">
                            <label for="radio-Fear">Fear</label>
                          </div>
                          <div class="col-4 col-12-small">
                              <input type="radio" id="radio-Sadness" name="radio" value="8">
                              <label for="radio-Sadness">Sadness</label>
                            </div>
                          </br>
                            <ul class="actions">
          										<li><input type="submit" name="submit" value="submit" class="button primary fit" /></li>
                              	<li><a href="label_images.php" class="button">Skip</a></li>
          										<li><a href="index.html" class="button">Quit</a></li>
          									</ul>
    </form>

    连接字符串:

    $user = "root";
    $pass = "";
    $db1 = "raw_images";
    $db2 = "labelled_images";
    $conn1 = mysqli_connect('localhost',$user,$pass,$db1);
    $conn2 = mysqli_connect('localhost',$user,$pass,$db2);
    if(!$conn1||!$conn2)
    {
    die(mysqli_error());
    }
    

    第一个数据库的图像检索:

       <div class="image fit">
       <?php
       //Connection with DB
    
       $sql = "SELECT * FROM tbl_raw_image WHERE id IN
        (SELECT id FROM (SELECT id FROM tbl_raw_image ORDER BY RAND() LIMIT 1) t)";
       $sth = $conn1->query($sql);
       $result=mysqli_fetch_array($sth);
       $id=$result['id'];
       $image=$result['image'];
       echo '<img src="data:image/jpeg;base64,'.base64_encode( $image ).'"/>'; ?>
           </div>
    

    图像存储在第二个数据库中:

    if(isset($_POST['submit'])){
    
    $label=$_POST['radio'];
    $query2="INSERT INTO tbl_labelled_image(image, label, id_in_raw_image_table) VALUES('$image','$label','$id'); ";
    $rs  = mysqli_query($conn2, $query2);
    }
    

2 个答案:

答案 0 :(得分:0)

将select语句返回的id以及用户添加的标签发送回服务器。

答案 1 :(得分:0)

您的查询真的很复杂。如果我正确理解您的问题,您可以尝试以下查询以获得所需的输出。

SELECT * FROM tbl_raw_image 
WHERE id = ROUND((RAND() * (MAX(id)-MIN(id)))+MIN(id));

INSERT IGNORE INTO tbl_raw_image_2 (id, name, BLOB) 
SELECT id, name, BLOB FROM tbl_raw_image 
WHERE id = ROUND((RAND() * (MAX(id)-MIN(id)))+MIN(id));

希望这适合你。