任何人都可以提出一些提示或修改意见,以使此代码更简洁,更快捷吗?这是我想到在星期五晚上做这件事的唯一方法,但是我敢肯定,必须有一种更有效的做事方法...
我知道正则表达式效率不高,但是我不能诚实地看到我还能如何做到这一点,特别是如果邮政编码数据可以来自以下任何内容:
e1 2be
e1ebe
e10ebe
e10 ebe
易北河
恩贝
等等...
非常感谢您提供的编码技巧,
H
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Amma Gawd! Someone ate our database!');
mysql_select_db($dbname);
$result = mysql_query("SELECT * FROM `Consumer`
WHERE left(`Postcode`,2) = 'E'
OR left(`Postcode`,1) = 'N'
OR left(`Postcode`,1) = 'W'");
while($row = mysql_fetch_array($result)) {
$email = $row['Email'];
if (preg_match("/^[Ee]{1}[0-9]{2}/",$row['Postcode'])) {
mysql_query("UPDATE `Consumer` SET `CONYES` = '1' WHERE `Email` = '$email'") or die ("Bugger");
$counter = $counter +1;
} elseif (preg_match("/^[Nn]{1}[0-9]{2}/",$row['Postcode'])) {
mysql_query("UPDATE `Consumer` SET `CONYES` = '1' WHERE `Email` = '$email'") or die ("Bugger");
$counter = $counter +1;
} elseif (preg_match("/^[Ww]{1}[0-9]{2}/",$row['Postcode'])) {
mysql_query("UPDATE `Consumer` SET `CONYES` = '1' WHERE `Email` = '$email'") or die ("Bugger");
$counter = $counter +1;
}
}
$result1 = mysql_query("SELECT * FROM `Consumer`
WHERE left(`postcode`,2) = 'BR'
OR left(`postcode`,2) = 'CR'
OR left(`postcode`,2) = 'EC'
OR left(`postcode`,2) = 'EN'
OR left(`postcode`,2) = 'KT'
OR left(`postcode`,2) = 'NW'
OR left(`postcode`,2) = 'RM'
OR left(`postcode`,2) = 'SE'
OR left(`postcode`,2) = 'SM'
OR left(`postcode`,2) = 'SW'
OR left(`postcode`,2) = 'TW'
OR left(`postcode`,2) = 'WC'
OR left(`postcode`,2) = 'BD'
OR left(`postcode`,2) = 'HG'
OR left(`postcode`,2) = 'LS'
OR left(`postcode`,2) = 'WF'
OR left(`postcode`,2) = 'YO'
OR left(`postcode`,2) = 'HD'
OR left(`postcode`,2) = 'HX'");
while($row1 = mysql_fetch_array($result1)) {
$email = $row1['Email'];
mysql_query("UPDATE `Consumer` SET `CONYES` = '1' WHERE `Email` = '$email'") or die ("Bugger");
$counter = $counter +1;
}
echo $counter;
mysql_close($conn);
最佳答案
您将其发布为PHP问题,但我认为最有效的方法是在一个SQL查询中完成所有操作,并让数据库来完成工作。您可以使用关键字“ RLIKE”来获取数据库以执行正则表达式匹配。您应该仔细阅读语法以获取所需的内容,但是为了开始您就需要这样的东西:
UPDATE `Consumer` SET `CONYES` = '1'
WHERE `Postcode` RLIKE '[EeNnWwBbMm][0-9]{2}'
OR LEFT(`postcode`,2) IN ('BR', 'CR', 'EC', 'EN', 'KT', 'NW', 'RM'.....
结果是更改的行数,可以直接将其分配给$ counter。