将ForEach循环写入数据库

时间:2014-08-01 16:49:49

标签: php mysql

这是一个愚蠢的问题,但我似乎无法找到答案。

我有一个foreach循环,可以找到特定链接上的所有图像。我想编码所有这些图像,然后将它们写入数据库。如果我将sql查询放在foreach循环中,那么为每个图像创建一个新行,如果我将sql查询放在foreach循环之外,则只写入第一个图像。如果我尝试分别编写图像和其余数据,插入会将$ newimage视为null并覆盖值。任何建议都会受到赞赏吗?

foreach($html->find('img') as $images) {
$newimage = json_encode($images->src);
echo $newimage;
}


$sql="INSERT INTO data (headline, images, email, date, category, area, number,   crawled, lastcrawled, description)
VALUES ('$headline', '$newimage', '$email','$date','$category','$area','$number', '$crawled', '$dt', '$description')";

2 个答案:

答案 0 :(得分:1)

希望这会对你有所帮助。

$newimages = array();
foreach($html->find('img') as $images) {
 $newimages[] = $images->src;
}

$newimage = json_encode($newimages);

相同的sql然后 -

$sql="INSERT INTO data (headline, images, email, date, category, area, number,   
crawled, lastcrawled, description) VALUES ('$headline', '$newimage',    
$email','$date','$category','$area','$number', '$crawled', '$dt', '$description')";

答案 1 :(得分:1)

根据您的评论,这应该可以为您提供所需的内容:

// create an array to hold the image sources
$store_images = array();
foreach($html->find('img') as $images) {
    // add the image sources to the array
    $store_images[] = $images->src;
}

// encode the entire array of images
$json_store_images = json_encode($store_images);

// store the encoded images along with the other data
$sql="INSERT INTO data (headline, images, email, date, category, area, number,   crawled, lastcrawled, description)
VALUES ('$headline', '$json_store_images', '$email','$date','$category','$area','$number', '$crawled', '$dt', '$description')";