简体   繁体   English

MySQL选择并插入到另一个表与PHP foreach循环

[英]Mysql Select and Insert into another table with Php foreach loop

I have a created a new table (colours) which has id and hex as columns, all existing ids are kept in the pics table along with the path of the picture, which will go into the new colours table with the many hex values. 我创建了一个新表(颜色),该表具有id和hex作为列,所有现有id与图片的路径一起保存在pics表中,它将进入具有许多hex值的新color表中。 I am using a class to extract the prominent colours from the picture as array of hex values. 我正在使用一个类从十六进制值数组中提取图片中的突出颜色。

This is the code so far: 到目前为止,这是代码:

$data = $conn->query('SELECT id,pic_path FROM pics WHERE pic_id = 1231');
while($row = $data->fetch()) {
    $image = new ColorsOfImage('images/'.$data['pic_path']);
    $colors = $image->getProminentColors();

    foreach($colors as $key => $val)
    {
        $sql = "INSERT INTO colours (pic_id,colour) VALUES (:pic_id,:colour)";
        $q = $conn->prepare($sql);
        $q->execute(array(':pic_id'=>$data['pic_id'],':colour'=>$val));
    }
}

But I get this error: 但是我得到这个错误:

Fatal error: Cannot use object of type PDOStatement as array

This is how it should look like this once it's populated: 填充后,它应该是这样的:

样本字段

当您想要的是$row['pic_id']时,您使用了$data['pic_id'] $row['pic_id']

This could be done with one single query, no php, no loop required 这可以通过一个查询来完成,不需要php,不需要循环

INSERT INTO colours (pic_id,colour)
SELECT id,pic_path FROM pics
WHERE pic_id = 1231

full details: https://dev.mysql.com/doc/refman/5.1/en/insert-select.html 完整详细信息: https : //dev.mysql.com/doc/refman/5.1/en/insert-select.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM