检查文件是否存在的有效方法并相应地更新SQL db

时间:2013-09-03 07:48:30

标签: php sql

我正在尝试检查文件夹中是否存在文件然后如果不存在,我想更新我的sql数据库。到目前为止,我循环遍历一个id数组,该数组应该有一个与数据库中的文件号对应的数字。这意味着我多次查询sql数据库一次。只进行一次查询是否可行且更有效?这是我的代码:

$photo_status = "SELECT id FROM photo_set_table WHERE Photo_added = 1";


$photo_added = mysql_query($photo_status);
if (!$photo_added) {
  die('Invalid query: ' . mysql_error());
}


$path = '/home/aXXXXXXX/public_html/';
$path .= '/images_android/images/';
$no_photo_array = array();

while($added = mysql_fetch_array($photo_added))
{

    if(!file_exists($path.$added[0].'.jpg')){
        array_push($no_photo_array, $added[0]);
    }

}//while added

$count_changes = 0;
foreach ($no_photo_array as $value) {
    $change_status = "UPDATE photo_set_table SET Photo_added = 0 WHERE id = $value";
    $photo_added2 = mysql_query($change_status);
    if (!$photo_added2) {
      die('Invalid query: ' . mysql_error());
    } else {
        $count_changes++;       
    }
} //foreach ($no_photo_array....
echo "The number of affected lines is: ".$count_changes;

mysql_close($connection);

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

$count_changes = 0;
if (count($no_photo_array) > 0) {
    $sInClause = implode(',', $no_photo_array);
    $sSql = "UPDATE photo_set_table SET Photo_added = 0 WHERE id IN (" . $sInClause . ")";
    $bStatus = mysql_query($sSql);
    if ($bStatus) {
        $count_changes = mysql_affected_rows();
    } else {
        die('Invalid query: ' . mysql_error());
    }
} //foreach ($no_photo_array....
echo "The number of affected lines is: ".$count_changes;