I use $_POST and index is undefined?

2019-08-27 17:23发布

问题:

I am using the code show below for a search and it is working. But when I try it to display another page with other results it says that “the index is undefined". I'm using again in this file but it does not solve anything. Can anyone tell me why is this happening?

The error is:

Notice: Undefined index: pesquisa in J:\xampp\htdocs\pesquisa3.php on line 32

The code is:

<?php

    session_start();

    if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
        header ("Location: login.php");
    }
?>  

<html>
    <head>
        <meta http-equiv="content-type" content="text/html"; charset="utf-8"/>
        <title>Registo</title>  
    </head>

    <body background="/images/farm.jpg">
        <center>
                <h1>Pesquisa em Mugidor</h1>
                <?php
                    $dbh = mysql_connect("127.0.0.1","root","")
                        or die("Erro ao ligar-me a base de dados -> ".mysql_error());
                    $db = mysql_select_db("users", $dbh)
                        or die("Erro ao escolher a base de dados -> ".mysql_error());
                    mysql_set_charset('utf8', $dbh);

                    // verificação da existência de pesquisa
                    $pesquisa = $_POST['pesquisa'];
                    if(!empty($_POST['pesquisa']))
                    {
                        // tabela onde vai ocorrer a pesquisa
                        $table = "mugidos";
                        // páginas adjacentes na numero de paginas de resultados
                        $adjacents = 1;
                        // explode as palavras colocadas na pesquisa em arrays
                        $arraySearch = explode(" ", $pesquisa);
                        // campos a pesquisar na tabela
                        $arrayFields = array(0 => "hashtag");
                        $countSearch = count($arraySearch);
                        $a = 0;
                        $b = 0; 
                        $query = "SELECT * FROM ".$table." WHERE (";
                        $countFields = count($arrayFields);
                        while ($a < $countFields)
                        {
                            while ($b < $countSearch)
                            {
                                $query = $query."$arrayFields[$a] LIKE '%$arraySearch[$b]%'";
                                $b++;
                                if ($b < $countSearch)
                                {
                                    $query = $query." AND ";
                                }
                            }
                            $b = 0;
                            $a++;
                            if ($a < $countFields)
                            {
                                $query = $query.") OR (";
                            }
                        }
                        $query = $query.")";
                        $query_result = mysql_query($query);
                        $numberrows = mysql_num_rows($query_result);
                        $pagenum= $numberrows / 4;
                        // resultados
                        echo '<h1>Resultados</h1>'."\n\n";
                        if($numberrows < 1)
                        {
                            echo '<p>Não foram encontrados resultados para "'.$pesquisa.'"</p>';
                        }
                        else
                        {
                            $page = (isset($_GET['page'])) ? (int)$_GET['page'] : 0; 
                            if($page) 
                            {
                            $inicio = ($page - 1) * 10;
                            $fim = ($page * 10);
                            }
                            else
                            {
                            $inicio = 0;
                            $fim = 4;
                            }
                            $query = $query."LIMIT $inicio, $fim";
                            $query_result2 = mysql_query($query);
                            echo '<p>Resultados da pesquisa de "'.$pesquisa.'":</p>'."\n\n";
                            while($row = mysql_fetch_assoc($query_result2))
                            {
                                $remugido = $row['mugido'] ;
                                $repostador = $row['postador'] ;
                                $rehashtag = $row['hashtag'] ;
                                $rerepostador = $row['repostador'];
                                // aqui aparece o output da pesquisa
                                if($rerepostador === NULL)
                                {
                                    echo "<table border='1' bordercolor='000000' style='background-color:FFFFFF' width='800' cellpadding='3' cellspacing='3'>";
                                    echo "<TR><TD width='70%'>","\n";
                                    echo "<strong>";
                                    echo $repostador;
                                    echo "</strong> ";
                                    echo $remugido;
                                    echo " <br><strong><font size='1'>";
                                    echo $row['timestamp'];
                                    echo "</strong></font>";
                                    echo "<form action='retweet.php' method='post'>";
                                    echo "<input type='hidden' value='";
                                    echo $remugido;
                                    echo "' name='remugido' style='height: 25px; width: 75px'><input type='submit' value='Re-Muuuu!' />";
                                    echo "<input type='hidden' value='";
                                    echo $repostador;
                                    echo "' name='repostador' />";
                                    echo "<input type='hidden' value='";
                                    echo $rehashtag;
                                    echo "' name='rehashtag' />";
                                    echo "</form>";
                                    echo "</TD>","\n";                  
                                    echo "</TR></table>" ,"\n";
                                }
                                else
                                {
                                    echo "<table border='1' bordercolor='000000' style='background-color:FFFFFF' width='800' cellpadding='3' cellspacing='3'>";
                                    echo "<TR><TD width='70%'>","\n";
                                    echo "<strong>";
                                    echo $repostador;
                                    echo "</strong> ";
                                    echo " via ";
                                    echo "<strong>";
                                    echo $row['repostador'];
                                    echo "</strong> ";
                                    echo $remugido;
                                    echo " <br><strong><font size='1'>";
                                    echo $row['timestamp'];
                                    echo "</strong></font>";
                                    echo "<form action='retweet.php' method='post'>";
                                    echo "<input type='hidden' value='";
                                    echo $remugido;
                                    echo "' name='remugido' style='height: 25px; width: 75px'><input type='submit' value='Re-Muuuu!' />";
                                    echo "<input type='hidden' value='";
                                    echo $repostador;
                                    echo "' name='repostador' />";
                                    echo "<input type='hidden' value='";
                                    echo $rehashtag;
                                    echo "' name='rehashtag' />";
                                    echo "</form>";
                                    echo "</TD>","\n";                  
                                    echo "</TR></table>" ,"\n";                 
                                }
                            }
                            echo "<form method='post'><a href='{$_SERVER['PHP_SELF']}?pagenum=$pagenum'>";
                            echo "<input type='hidden' value='";
                            echo $pesquisa;
                            echo "' name='pesquisa'><INPUT TYPE='submit' VALUE='Proxima pagina'></a></form>";
                        }
                    }
                    else
                    {
                        echo ("Insira pelo menos um termo de pesquisa.<br />Redirecionando em 3 segundos.");
                        header ("Refresh: 3; url=page5.php");
                        die();
                    }
                ?>
        </center>
    </body>
</html>

回答1:

Change

$pesquisa = $_POST['pesquisa'];

to

$pesquisa = (isset($_POST['pesquisa'])) ? $_POST['pesquisa'] : '';
// or
$pesquisa = @$_POST['pesquisa']; // suppress warning if not set

// and then change 
if(!empty($_POST['pesquisa']))
// to
if(trim($pesquisa) != ''))

You are trying to assign $_POST['pesquisa']; but that value is only set if the search form was filled out.

Also change:

echo "<form method='post'><a href='{$_SERVER['PHP_SELF']}?pagenum=$pagenum'>";
echo "<input type='hidden' value='";
echo $pesquisa;
echo "' name='pesquisa'><INPUT TYPE='submit' VALUE='Proxima pagina'></a></form>";

to

echo "<form method='post' action='{$_SERVER['PHP_SELF']}?pagenum=$pagenum'>";
echo "<input type='hidden' value='";
echo htmlspecialchars($pesquisa);
echo "' name='pesquisa'><INPUT TYPE='submit' VALUE='Proxima pagina'></form>";


回答2:

This is not correct:

                echo "<form method='post'><a href='{$_SERVER['PHP_SELF']}?pagenum=$pagenum'>";
                echo "<input type='hidden' value='";
                echo $pesquisa;
                echo "' name='pesquisa'><INPUT TYPE='submit' VALUE='Proxima pagina'></a></form>";

You are putting an input element inside a a tag. That's just wrong, you need to add another hidden variable to your form with the page-number so that you can get it when the form is re-posted.

Something like:

echo "<form method='post'>";
echo "<input type='hidden' name='pagenum' value='" . (intval($_POST['pagenum']) + 1) . "' />";
echo "<input type='hidden' value='";
echo $pesquisa;
echo "' name='pesquisa'><INPUT TYPE='submit' VALUE='Proxima pagina'></form>";

After that obviously you have to get the value of pagenum and adjust the limit clause in your query to accommodate it.

Edit: I missed it the first time, you are using:

$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 0;

So you need to use the variable $page in the form at the bottom as well, instead of $pagenum (I use post, but it's the same for get):

$page = (isset($_POST['page'])) ? (int)$_POST['page'] : 0;

...

echo "<form method='post'>";
echo "<input type='hidden' name='page' value='" . (intval($_POST['page']) + 1) . "' />";
echo "<input type='hidden' value='";
echo $pesquisa;
echo "' name='pesquisa'><INPUT TYPE='submit' VALUE='Proxima pagina'></form>";