April 25, 2012

Notice: Undefined index: in C:wampwwwsomygmsa.php on line 142

Question by admin

I got an error whenever I run this php code on my local web server:

<?php
@ require_once ('C:wampwwwConnectionskoneksi.php');
session_start();
if (!isset($_SESSION['id']))
{
    header("Location:index.php");
}
$sql = "SELECT * FROM pasien WHERE noreg = 1122312131";
$query = mysql_query($sql) or die(mysql_error());
$data2 = mysql_fetch_array($query);

?>

            <form id="form1" name="form1" method="post" action="#">
          <table width="804" border="0" id="inputdata" style="border-collapse:collapse">
            <tr>
              <th width="8" rowspan="3" bgcolor="#CCCCCC" scope="row">&nbsp;</th>
              <th width="104" height="50" bgcolor="#CCCCCC" scope="row"><div align="right">Kode Pasien</div></th>
              <td width="250" bgcolor="#CCCCCC"><label for="nama"></label>
                <label for="noreg"></label>
                <div align="left">
                <input name="noreg" type="text" id="noreg" size="15" maxlength="13">
                <input type="submit" name="view" id="view"  value="View">       <?php
                @ include_once ('database.php');
                $view = $_POST['view'];
                $noreg = $_POST['noreg'];
                if($view){
                    $_POST[$noreg];
                }
                ?>

This is the error:

( ! ) Notice: Undefined index: view in C:wampwwwsomygmsa.php on line 139

and

( ! ) Notice: Undefined index: noreg in C:wampwwwsomygmsa.php on line 140

Thanks for any help, will be appreciated.

-admin

Answer by Starx

You are initializing those two variables with the array item does not exists.

$view = $_POST['view'];
$noreg = $_POST['noreg'];

Clearly shows that the view and noreg are not coming from the POST method. You should check to confirm this. Use var_dump($_POST); to see the posted data.

When you are coding, you should make sure that the code you are writing will execute on all cases as much as possible. In your case, initialize the variables before or use isset to check and initialize again.

$view = isset($_POST['view']) ? $_POST['view'] : '';
$noreg = isset($_POST['noreg']) ? $_POST['noreg'] : '';

Now that it is being pointed out…. The page by default will have *no POST variables *, so you have filter such cases out

if(isset($_POST) && count($_POST)) {
    @ include_once ('database.php');
    $view = $_POST['view'];
    $noreg = $_POST['noreg'];
    if($view){
        $_POST[$noreg];
    }
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!