2011-10-24 7 views
1

配列内の値にフォーム入力を一致させることに問題があります。は変数を配列内の値に一致させることができません

if(isset($_POST['city'])){ 

$city = mysql_real_escape_string($_POST['city']); 
$cities = array('Alamance','Archdale','Arlington'); 
$count = count($cities); 
for($x=1; $x<=$count; $x++){ 
    if($city === $cities[$x]){ # match } 
     else{ # no match, set error } 
} 

} else{ # city is not set, set error } 

if(isset($_POST['county'])){ 
# county is set. make sure that it is actually a triad county 

$county = mysql_real_escape_string($_POST['county']); 
$counties = array('Alamance','Davidson','Davie'); 
foreach($counties AS $x){ 
    if($county != $x){ # no match, set error } 
     else{ # match } 
} 
} else { # county is not set, set error } 

私がやりたいすべてが、それぞれの配列に1への入力の都市や郡に一致するか、それが一致しない場合、エラーが設定されます。

は、ここに私のコードです。私はこれまで何度もやったことがあるので、ここではうまくいかない理由を理解できませんが、私はそれをすべて見すぎて余分な目を必要としているかもしれません。

誰かがこのコードをチェックして、どこが間違っているのか確認できますか?

+3

だけでいくつかのポインタ:あなたはあなたにユーザー入力を保存している場合にのみ使用してください() '既存の配列と' mysql_real_escape_stringの内の値をテストするために 'in_array()'メソッドを使用することができますデータベース。 –

+0

なぜ1つの回答を受け入れなかったのですか? –

答えて

1

この行が間違っている:それはあるべき

for($x=1; $x<=$count; $x++){ 

for($x=0; $x<$count; $x++){ 

と私もこれに変更することをお勧め:この中

if($county != $x) 

if($county !== $x) 
0

in_arrayの機能を調べることをお勧めします。例:

if (isset($_POST['city'])) 
{ 
    $city = $_POST['city']; 
    $cities = array('Alamance','Archdale','Arlington'); 
    if (in_array($city, $cities)) 
    { 
     # match 
    } 
    else 
    { 
     # no match, set error 
    } 
} 
else 
{ 
    # city is not set, set error 
} 
関連する問題