2017-04-25 57 views
0

我想更新img列,因此每个单元格的值都为images文件夹中的一个img路径/名称。根据图像路径和名称更新列

$path = "../images/"; 
$items = glob($path . '*.jpg'); 
foreach($items as $img) { 

$db->query("update posts set img ='" . $img . "'"); 

结果 - 所有单元格都有相同的内容!

任何帮助?

+0

您将需要一个where子句来告诉它更新哪一行。你的SQL语句告诉它更新所有的行。 –

+0

如果您只想更新一条记录,则需要带有ID(或该记录的某个其他唯一标识符)的“WHERE”子句。否则,数据库不知道你打算更新什么记录。 –

+0

@MagnusEriksson,我想要更新整个列,即每个单元格,但使用不同的单一img路径 – bonaca

回答

1

我将首先把所有的帖子ID的,所以你可以通过一个更新它们之一。

这是一些伪代码。或许,这将需要一些修改(至少是第一部分,你在哪里得到的所有帖子的ID):

// Get all post ids 
// Change the database call to match your db library 
$ids = $db->query("select id from posts"); 

$i = 0; 
foreach (glob('../images/*.jpg') as $img) { 
    if (!array_key_exists($i, $ids)) { 
     // There's no more ids, so let's stop the loop 
     // and consider the script to be done. 
     break; 
    } 

    // Update one record with one image 
    $db->query("update posts set img = '{$img}' where id = " . $ids[$i]['id']); 

    // Increment the index so we will get the next 
    // post id during the next iteration. 
    $i++; 
} 
0

您需要在查询中使用where子句来在更新内容之前过滤结果。 例如

update post set img = 'your_image_path.png' where post_id='your_post_id';] 

阅读this更多信息