PHP: Undefined index notice when redirecting search results to new page
<p>My website has a search function which works fine - only now I want the search results to be displayed on a new page (and not the same page). To this end I made use of the global variable <code>$_SESSION</code> (to make the array available in the new location) and <code>header("Location:</code> to redirect to the dedicated page for results.</p>

<p>On running the search, the following errors are generated: </p>

<ul>
<li>Notice: Undefined index: search_output in final.php on line 12   </li>
<li>Warning: Invalid argument supplied for foreach() in final.php on line
12</li>
</ul>

<p>It's the first time I'm using $_SESSION and don't know how to fix these errors.<br>
Would appreciate any insight in understanding what's wrong.</p>

<p>Here are the pages:<br>
<strong>index.php</strong></p>

<pre><code>&lt;?php require_once  ('setup.php');
require_once  ('function.php');

?&gt;

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;body&gt;


&lt;?php
if ( isset( $_GET['s'] ) ) {
  $search_results='';
  $search_term = htmlspecialchars($_GET['s'], ENT_QUOTES);
  $search_results = search($conn, $search_term);  
  }
?&gt;

&lt;form role="search" method="get" class="search-form" action=""&gt;
                &lt;label&gt;
                &lt;input type="search" class="search-field" placeholder="Search" value="searchitem" name="s"&gt;
                &lt;/label&gt;
                &lt;input type="submit" class="search-submit" value="Search"&gt;              
&lt;/form&gt;

  &lt;?php if (isset($search_results)) : 
        $_SESSION['search_output'] = $search_results;
        header("Location: final.php");
        exit;
   endif; ?&gt;

&lt;body&gt;
&lt;/html&gt;
</code></pre>

<p><strong>function.php</strong></p>

<pre><code>&lt;?php

function search($conn, $search_term) {
   if (session_id() === "") { session_start(); }
    $sanitized =  $conn-&gt;real_escape_string($search_term);

    $query = $conn-&gt;query("
      SELECT * FROM news WHERE title LIKE '%{$sanitized}%' OR body LIKE '%{$sanitized}%' OR sources LIKE '%{$sanitized}%' OR date LIKE '%{$sanitized}%'");


    if ( ! $query-&gt;num_rows ) {
      return false;
    }


    while( $row = $query-&gt;fetch_object() ) {
      $rows[] = $row;
    }

    $search_results = array(
      'count' =&gt; $query-&gt;num_rows,
      'results' =&gt; $rows,
    );

    return $search_results;
  }


  ?&gt;
</code></pre>

<p><strong>final.php</strong></p>

<pre><code>&lt;?php session_start();  
?&gt;

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;body&gt;


&lt;?php
foreach($_SESSION['search_output'] as $value){
     echo $value['results']-&gt;title;
}
?&gt;

&lt;body&gt;
&lt;/html&gt;
</code></pre>

<p><strong>setup.php</strong></p>

<pre><code>&lt;?php
$hn = 'localhost';
$db = 'boh';
$un = 'water';
$pw = 'water'; 

#DB Connection:
 $conn = new mysqli($hn, $un, $pw, $db);
 if ($conn-&gt;connect_error) die($conn-&gt;connect_error);
?&gt;
</code></pre>