我有一个工作脚本,可以选择所有表中的图像字段,如果物理文件不存在则清空它们的值。
$query1 = "SELECT table_name,column_name
FROM information_schema.columns
WHERE table_schema='schemaname' AND column_name like '%image%' or column_name='video'";
$result1 = mysql_query($query1) or die(mysql_error() . " -- " . $query1);
while($row1 = mysql_fetch_row($result1)){
if (!strpos($row1[0],'backup') > 0){
$sql = "Select COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME = '".$row1[0]."' AND EXTRA = 'auto_increment'";
$resultcol = mysql_query($sql);
$rowcol = mysql_fetch_row($resultcol);
$query2 = "SELECT " . $row1[1] . ", " .$rowcol[0] . "
FROM " . $row1[0] . "
WHERE " . $row1[1] . " != '' AND " . $row1[1] . " IS NOT NULL
";
echo $query2 . "<br>";
$result2 = mysql_query($query2) or die(mysql_error() . " -- " . $query2);
while ($rowdb = mysql_fetch_row($result2)){
if (!strpos($rowdb[0],'facebook') > 0 && !file_exists($img_root.'/'.$rowdb[0])){
$sql = "UPDATE ".$row1[0]." SET ". $row1[1] . " = '' WHERE " . $rowcol[0]. "= ".$rowdb[1];
echo $sql . "<br><br>";
$delete_count++;
//mysql_query("UPDATE ".$row1[0]." SET ". $row1[1] . " = '' WHERE id = ".$row1["id"]);
}
}
}
}
脚本工作正常,但需要时间,我想知道是否有更聪明的方法(更优化)来获得相同的功能?感谢
答案 0 :(得分:0)
您有几种选择。
第一个,恕我直言最好的选择 - 是使用ORM - 我推荐Idiorm,Doctrine或Propel。
然后,你会使用(在idiorm中)fetch_all
之类的东西并循环使用,而不是通过mysql_fetch_row()
其次,您应该切换到mysqli
- 您正在使用的函数在PHP5.5中已弃用
第三 - 您可以使用mysql_fetch_array
或mysql_fetch_all
(我不确定,但我会选择后者)
这里的关键是:
不要循环mysql函数。
答案 1 :(得分:0)
性能方面,问题在于您循环遍历结果集,并对每一行执行查询。
然而,对于您的输出,很难消除这一点。否则,您可以在单个SQL语句中执行整个脚本。
最小化清除只删除其中一个选项: -
<?php
$query1 = "SELECT a.table_name, a.column_name, b.COLUMN_NAME AS auto_inc_col
FROM information_schema.columns a
INNER JOIN information_schema.columns b
ON a.table_name = b.table_name AND b.EXTRA = 'auto_increment'
WHERE table_schema='schemaname' AND column_name like '%image%' or column_name='video'";
$result1 = mysql_query($query1) or die(mysql_error() . " -- " . $query1);
while($row1 = mysql_fetch_assoc($result1))
{
if (!strpos($row1['table_name'],'backup') > 0)
{
$query2 = "SELECT " . $row1['column_name'] . ", " .$row1['auto_inc_col'] . "
FROM " . $row1['table_name'] . "
WHERE " . $row1['column_name'] . " != '' AND " . $row1['column_name'] . " IS NOT NULL
";
echo $query2 . "<br>";
$result2 = mysql_query($query2) or die(mysql_error() . " -- " . $query2);
while ($rowdb = mysql_fetch_row($result2))
{
if (!strpos($rowdb[0],'facebook') > 0 && !file_exists($img_root.'/'.$rowdb[0]))
{
$sql = "UPDATE ".$row1['table_name']." SET ". $row1['column_name'] . " = '' WHERE " . $row1['auto_inc_col']. "= ".$rowdb[1];
echo $sql . "<br><br>";
$delete_count++;
//mysql_query("UPDATE ".$row1['table_name']." SET ". $row1['column_name'] . " = '' WHERE id = ".$row1["id"]);
}
}
}
}
?>