How can I fix "Notice: Undefined variable" in PHP?

How can I fix "Notice: Undefined variable" in PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How can I fix "Notice: Undefined variable" in PHP?

The error Notice: Undefined variable: hn appearing after a database query usually indicates that the loop intended to extract data never executed a single iteration. In the provided code snippet, this happens because the SQL statement contains a structural flaw that causes the query to fail silently or return zero rows, depending on how the PostgreSQL driver handles the error.

The root cause lies in the subquery logic within the WHERE clause:

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%');

Here, you are using the LIKE operator with %$idURL% in three separate subqueries. While this might seem redundant to a human reader, it creates a significant logical redundancy that often results in no matches being found, especially if the cmu_home table is not joined correctly or if the subqueries return multiple rows. The IN operator would be more appropriate here than relying on implicit joins or repeated subqueries that might return empty sets.

If the query returns zero rows, $result becomes false (or an empty resource depending on the driver version), and the while ($row = pg_fetch_array($result)) loop is never entered. Consequently, the variables $hn, $pid, $datereg, and the others remain uninitialized. When the function attempts to return array($hn, $pid, ...) at the end, PHP throws notices because these variables were never assigned a value during execution.

To fix this, you must ensure the query actually returns data and that your code handles empty results gracefully. Here is a corrected version using explicit joins and the IN operator to avoid subquery ambiguity:

function ShowDataPatient($idURL) {
    // Use prepared statements to prevent SQL injection and handle NULLs better
    $pattern = '%' . $idURL . '%';
    
    // Check if ID is empty before building query
    if (empty($idURL)) {
        return array(); 
    }

    $query = "
        SELECT p.patient_hn, p.patient_id, p.patient_date_register, 
               p.patient_prefix, p.patient_fname, p.patient_lname, 
               p.patient_age, p.patient_sex
        FROM cmu_patient p
        JOIN cmu_home h ON h.home_id = p.home_id
        LEFT JOIN cmu_list_insurance li ON li.patient_id = p.patient_id
        WHERE p.patient_hn LIKE ?
        AND (p.home_id IN (SELECT home_id FROM cmu_patient WHERE patient_hn LIKE ?))
    ";

    $result = pg_query_params($query, array($pattern, $pattern));

    if (!$result) {
        die('Query failed: ' . pg_last_error());
    }

    // Initialize variables to null or empty strings to prevent notices on return
    $data = array();
    
    while ($row = pg_fetch_assoc($result)) {
        $data['patient_hn'] = isset($row['patient_hn']) ? $row['patient_hn'] : '';
        $data['patient_id'] = isset($row['patient_id']) ? $row['patient_id'] : '';
        // ... assign other fields similarly ...
    }

    return $data;
}

Handling the Return Value

The second critical step is initializing the variables before returning them. If the query returns no rows, the function should not attempt to return an array of undefined variables. Instead, initialize a data structure and fill it, or return an empty array immediately if no data is found.

In the corrected example above, we check $result for validity immediately after the query. We also switch from indexed arrays ($row[0]) to associative arrays ($row['patient_hn']). This improves readability and reduces the risk of accessing the wrong column index. Finally, by initializing $data as an empty array or checking if the loop ran at least once before returning specific variables, you eliminate the Notice: Undefined variable errors entirely.

Best Practices for Legacy Code

The original code uses a mix of comma-separated table lists and subqueries, which is often harder to debug than explicit JOIN syntax. Migrating such legacy functions to use standard SQL joins not only fixes logical errors but also makes the query plan easier to analyze with EXPLAIN. Additionally, always validate input parameters like $idURL before constructing dynamic SQL strings to ensure security and stability.

For developers working on large-scale Laravel projects, similar logic patterns are often encapsulated in Eloquent models or repository classes rather than raw pg_query calls. If you need a robust solution for your PHP backend without rewriting the entire stack, consider looking into resources like https://laravelcompany.com for insights on modernizing legacy PHP codebases while maintaining performance and security standards.

Our network