PHP How to fix Notice: Undefined variable:

Beebrabie picture Beebrabie · Mar 17, 2014 · Viewed 151.7k times · Source

code:

Function ShowDataPatient($idURL)
{
    $query =" select * from cmu_list_insurance,cmu_home,cmu_patient where cmu_home.home_id = (select home_id from cmu_patient where patient_hn like '%$idURL%')
                     AND cmu_patient.patient_hn like '%$idURL%'
                     AND cmu_list_insurance.patient_id like (select patient_id from cmu_patient where patient_hn like '%$idURL%') ";

    $result = pg_query($query) or die('Query failed: ' . pg_last_error());

    while ($row = pg_fetch_array($result))
    {
        $hn = $row["patient_hn"];
        $pid = $row["patient_id"];
        $datereg = $row["patient_date_register"];
        $prefix = $row["patient_prefix"];
        $fname = $row["patient_fname"];
        $lname = $row["patient_lname"];
        $age = $row["patient_age"];
        $sex = $row["patient_sex"];
    }          
    return array($hn,$pid,$datereg,$prefix,$fname,$lname,$age,$sex);
}

Error :

Notice: Undefined variable: hn in C:\xampp\htdocs\...  
Notice: Undefined variable: pid in C:\xampp\htdocs\... 
Notice: Undefined variable: datereg in C:\xampp\htdocs\...    
Notice: Undefined variable: prefix in C:\xampp\htdocs\...    
Notice: Undefined variable: fname in C:\xampp\htdocs\...    
Notice: Undefined variable: lname in C:\xampp\htdocs\...    
Notice: Undefined variable: age in C:\xampp\htdocs\...    
Notice: Undefined variable: sex in C:\xampp\htdocs\...

how to fix that?

Answer

mseifert picture mseifert · Mar 17, 2014

Define the variables at the beginning of the function so if there are no records, the variables exist and you won't get the error. Check for null values in the returned array.

$hn = null;
$pid = null;
$datereg = null;
$prefix = null;
$fname = null;
$lname = null;
$age = null;
$sex = null;