2012-07-07 72 views
0

我想根据提交的表单的内容定义一个变量,针对MySQL数据库进行检查,但preg_match和$变量匹配不会一起工作。 他们独立工作,但不在一起。PHP elseif或语句不起作用

我已经打印出每个步骤中的每个变量,并证明提交,比较和检索的数据始终存在,但在比较ifelse语句中的两个变量时无法定义变量:elseif(!pret_match(“/ bt/i “,$ zip)或$ country!=='Ireland')

过程如下: 表单提交 - >比较变量与数据库 - >输出变量取决于数据库比较。

样的形式提交(例子):

FBID(12345678901)

城市(贝尔法斯特)

国家(英国)

拉链(BT1 1DS)

这是(减少)代码导致问题:

$country = $location['country']; //good value: Ireland/bad value: Italy(or empty) 
    $zip = $location['zip']; //good value: BT1 1DS/bad value: 00(or empty) 

    if ($fbid == $id) { //this works 
    $confirmpage = '<h3>Sorry, this page is already in the table.</h3>'; 
    } elseif (!preg_match("/bt/i",$zip) or $country !== 'Ireland') { //confirm location 
    $confirmpage = '<h3>This page is not in Northern or Southern Ireland</h3>'; 
    } else { //success, page can be submitted 
    $confirmpage = '<h3>Confirm Page</h3>'; 
    } 

的代码不工作是:

 elseif (!preg_match("/bt/i",$zip) or $country !== 'Ireland') 

当我删除这条语句的脚本的其余部分工作正常。 如果选项1是负面的,有了这个说法,结果总是选择2,即使提交的表单包括BT在zip或爱尔兰因为该国的开始:

$confirmpage = '<h3>This page is not in Northern or Southern Ireland</h3>'; 
+2

运算符'具有或'不一样的[优先](http://php.net/ language.operators.precedence)为'||'。改用'||'代替。 – Gumbo 2012-07-07 17:22:25

+0

@Gumbo:从链接页面可以看到,'or'和'||'的优先级低于'!==',所以这里没关系。 – oxc 2012-07-07 21:35:13

+0

你的问题并不清楚预期的结果是什么。如果'bt'不在拉链中,或者他们没有选择爱尔兰作为国家,我们认为你的条件可以翻译为“显示'此页面不在北部或南部爱尔兰'',我认为你的逻辑倒退了,并且这两个都应该是正数? – ernie 2012-07-12 16:22:28

回答

0

尝试

elseif (preg_match("/bt/i",$zip) == 1 || $country != 'Ireland') 
+1

'preg_match'实际上返回匹配数(0或1) 当然,你可以匹配0 == false,但是实际上并不需要,并且'preg_match'如果发生错误,返回'false'(无效模式等),你真的应该只使用'==='比较它'false',以避免混淆。 – oxc 2012-07-07 21:36:36

+0

感谢你的支持。爱尔兰条目输出正确,但正确的邮政编码返回一个坏条目。 – 2012-07-08 17:11:53

+0

那么呢? – maxhud 2012-07-08 18:13:23

0

我创建了一个基本的PHP页面代码并复制到您的代码中 - 然后将$ country和$ zip手动设置为好或不好的值 - 它按预期方式工作,因此表明它与preg_match没有问题。

0

通过更改检查的执行方式来排序。 相反的:如果“条件”或“条件2”,我用ifelse检查postives:

$confirmpage = '<h3>This page is not in Northern or Southern Ireland</h3>'; 
    if ($fbid == $id) { 
$confirmpage = '<h3>Sorry, this page is already in the table.</h3>'; 
} elseif (preg_match("/bt/i",$zip)) { //BT post code present 
$confirmpage = $confirm; 
} elseif ($country == 'Ireland') { // //Ireland present 
$confirmpage = $confirm; 
} else { //confirm page 
$confirmpage = '<h3>This page is not in Northern or Southern Ireland</h3>';