PHP - sorgu dizesini kullanır sayfa gösteriliyor, ancak herhangi bir değişken olmadan

4 Cevap php

Ben Error.php adında bir sayfa var. Ben atamış hata kodu gelen mesaj görüntüler böylece değişkenler genelde sorgu dizesi kullanarak kendisine iletilen.

Örnek: Error.php id = 1

İşte aşağıda benim sayfa bölümü:

<?php
if($_GET["id"] == "0")
{
  echo "Display certain information...";
}
elseif($_GET["id"] == "1")
{
  echo "Display certain information...";
}
elseif($_GET["id"] == "2")
{
  echo "Display certain information...";
}
elseif($_GET["id"] == "3")
{
  echo "Display certain information...";    
}
else
{
  echo "Display certain information...";
}
?>

Tüm bilgiler çalışıyor, ama hiçbir sorgu dizesi varsa tek sorun (sadece "Error.php" olarak bırakarak),, bu ": id in .... Undefined index" diyerek hataları görüntüler. Bir sorgu dizesi olmadıkça Error.php unaccessible yapmak için bir yolu var mı? Benim kod gramer yanlış ise ben PHP çok yeniyim, üzgünüm. Teşekkür ederim.

4 Cevap

: Array_key_exists () kontrol edin ve orada olmadığını görmek için kullanın

<?php

if(array_key_exists("id", $_GET)) 
{
    if($_GET["id"] == "0")
    {
      echo "Display certain information...";
    }
    elseif($_GET["id"] == "1")
    {
      echo "Display certain information...";
    }
    elseif($_GET["id"] == "2")
    {
      echo "Display certain information...";
    }
    elseif($_GET["id"] == "3")
    {
      echo "Display certain information...";    
    }
    else
    {
      echo "Display certain information...";
    }
}
else
{
  // no query id specified, maybe redirect via header() somewhere else?
}

?>

Bu mesajı bir hata ama bir bildirim değildir. Bu web uygulamasında bildirim iletileri devre dışı bırakabilir ve (geliştirirken onun para cezası) üretim hizmete giderken zaten bunu yapmak için tavsiye edilir.

Sen error_reporting dahil değil php.ini ayarı yapabilirsiniz E_NOTICE

Sen anahtar 'id' array $ _GET ayarlanmış olup olmadığını kontrol etmek için isset kullanmalısınız. Basit bir dize arama için yerine bir dizi kullanmak gerekir eğer-then-else ve anahtarı.

$errorMessages = array(
    "0" => "Display certain information...";
    "1" => "Display certain information...";
    "2" => "Display certain information...";
    "3" => "Display certain information...";
);

if (!isset($_GET['id']) || !isset($errorMessages[$_GET['id']])) {
    $message = 'No predefined error message';
    //or redirect
} else {
    $message = $errorMessages[$_GET['id']];
}
echo $message;