"Undefined index" and "Cannot access Empty Property"

Asked

Viewed 99 times

0

Hello, folks! Although there are many posts here in Stack regarding this issue, none of them was enough for me to fix mine.

I am creating an admin panel of a website whose homepage is basically a calendar, on whose dates containing events it is possible to click and open pages with classroom contents.

In admin.php, I created a form for registering new dates at the same time that a page with some features is automatically created for the teacher to add content to it. The form has 3 fields: Title, Date and Meeting.

So, I was editing the file by registering.php and decided to have the same name written by the teacher in the last field of the form (called "date") automatically included in the database in the title field, plus ". php" (which would become the filename of the new page created). Then I would delete the "date" field, so no one would write anything inside. But I didn’t even do that, since the error described in the title of this post occurred and the entire admin page was disfigured, even disappearing the calendar.

It turns out, although I was working on the.php file, the error describes a problem in.php calendar, which was working normally until then and was not touched.

Anyway, if anyone can shed some light, I’d really appreciate it.

That is the error:

inserir a descrição da imagem aqui

*calendar.php line 12:

 $encontro = $info['encontro'];

*calendar.php line 20:

 'encontro' => $row->{$encontro}

Here are the codes:

in admin.php (in the part that matters):

<!--cadastrar evento--> 
    <div class="item-main-admin">

        <p2><center>
        <form name="cadastrarevento" method="post" action="cadastrando.php">
        Título: <input type="text" name="titulo" value="encontro-"/> </br>
        Data: <input type="text" name="data" placeholder="aaaa/mm/dd" /> </br>
        Encontro: <input type="text" name="encontro" /> </br>
        <input type="submit" value="Cadastrar evento" />
        </form>
        </p2></center>
    </div>




<!--calendario-->
<div class="item-main-admin">
    <?php 
    $eventos = montaEventos($info);
    montaCalendario($eventos); 
    ?>
</div>

<script type="text/javascript" src="/administrador/calendario/jquery.js"></script>
    <script type="text/javascript" src="/administrador/calendario/functions.js"></script>


In registering.php:

<?php
error_reporting (E_ALL & ~ E_NOTICE & ~ E_DEPRECATED);
$host = "localhost";
$user = "root";
$pass = "";
$banco = "calendario";
$conexao = mysql_connect($host, $user, $pass) or die(mysql_error());
mysql_select_db($banco) or die(mysql_error());
?>


<?php
mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
?>


<?php

$titulo=$_POST['titulo'];
$data=$_POST['data'];
$encontro=$_POST['encontro'];


$myFile = "$titulo.php";


$result = mysql_query("SELECT titulo FROM eventos WHERE titulo = '$titulo'");

if (mysql_num_rows($result)>0) {
        echo "O título $titulo já existe. Crie um diferente.";
        } else {

    $sql = mysql_query("INSERT INTO eventos(titulo, data, encontro) 
    VALUES('$titulo', '$data', '$encontro')");


$fh = fopen($myFile, 'w');

$stringData = "<html><?php include 'template.php';?></html>";   


fwrite($fh, $stringData);
//header('Location: ' . $myFile);
fclose($fh);


?>



<div class="cadastro_ok">
<div id="item-cadastro_ok">
    <img src="imagens/ok.png" />
</div>
<div id="item-cadastro_ok">
    <?php echo "Cadastro efetuado com sucesso!"; ?>
</div>
</div>

<?php } ?>



<?php
echo '<meta http-equiv="refresh" content="3;URL=admin.php" />';
?>

</div>

</body>

</html>

****OBS.: I had put so ($Myfile in the place of $meeting), and then I had the mistake, although it doesn’t seem to come from there:

$sql = mysql_query("INSERT INTO eventos(titulo, data, encontro) 
    VALUES('$titulo', '$data', '$myFile')");

And in the.php calendar:

<?php

function num($num){
    return ($num < 10) ? '0'.$num : $num;
}
function montaEventos($info){
    global $pdo;
    //tabela, data, titulo, encontro
    $tabela = $info['tabela'];
    $data = $info['data'];
    $titulo = $info['titulo'];
    $encontro = $info['encontro'];
    $eventos = $pdo->prepare("SELECT * FROM `".$tabela."` ");
    $eventos->execute();
    $retorno = array();
    while($row = $eventos->fetchObject()){
        $dataArr = date('Y-m-d', strtotime($row->{$data}));
        $retorno[$dataArr] = array(
            'titulo' => $row->{$titulo},
            'encontro' => $row->{$encontro}
        );
    }
    return $retorno;
}
function diasMeses(){
    $retorno = array();
    for($i = 1; $i<=12;$i++){
        $retorno[$i] = cal_days_in_month(CAL_GREGORIAN, $i, date('Y'));
    }
    return $retorno;
}
function montaCalendario($eventos = array()){
    $daysWeek = array(
        'Sun',
        'Mon',
        'Tue',
        'Wed',
        'Thu',
        'Fri',
        'Sat'
    );
    $diasSemana = array(
        'Dom',
        'Seg',
        'Ter',
        'Qua',
        'Qui',
        'Sex',
        'Sab'
    );
    $arrayMes = array(
        1 => 'Janeiro',
        2 => 'Fevereiro',
        3 => 'Março',
        4 => 'Abril',
        5 => 'Maio',
        6 => 'Junho',
        7 => 'Julho',
        8 => 'Agosto',
        9 => 'Setembro',
        10 => 'Outubro',
        11 => 'Novembro',
        12 => 'Dezembro'
    );
    $diasMeses = diasMeses();
    $arrayRetorno = array();
    for($i =1; $i <= 12; $i++){
        $arrayRetorno[$i] = array();
        for($n=1; $n<= $diasMeses[$i]; $n++){
            $dayMonth = gregoriantojd($i, $n, date('Y'));
            $weekMonth = substr(jddayofweek($dayMonth, 1),0,3);
            if($weekMonth == 'Mun') $weekMonth = 'Mon';
            $arrayRetorno[$i][$n] = $weekMonth;
        }
    }
    echo '<a href="#" id="volta">&laquo;</a><a href="#" id="vai">&raquo;</a>';
    echo '<table border="0" width="100%">';
    foreach($arrayMes as $num => $mes){
        echo '<tbody id="mes_'.$num.'" class="mes">';
        echo '<tr class="mes_title"><td colspan="7">'.$mes.'</td></tr>';
        echo '<tr class="dias_title">';
        foreach($diasSemana as $i => $day){
            echo '<td>'.$day.'</td>';
        }
        echo '</tr><tr>';
        $y = 0;
        foreach($arrayRetorno[$num] as $numero => $dia){
            $y++;
            if($numero == 1){
                $qtd = array_search($dia, $daysWeek);
                for($i=1; $i<=$qtd; $i++){
                    echo '<td></td>';
                    $y+=1;
                }
            }
            if(count($eventos) > 0){
                $month = num($num);
                $dayNow = num($numero);
                $date = date('Y').'-'.$month.'-'.$dayNow;
                if(in_array($date, array_keys($eventos))){
                    $evento = $eventos[$date];
                    echo '<td class="evento"><a href="'.$evento['encontro'].'" title="'.$evento['titulo'].'">'.$numero.'</a></td>';
                }else{
                    echo '<td class="dia_'.$numero.'">'.$numero.'</td>';
                }
            }else{
                echo '<td class="dia_'.$numero.'">'.$numero.'</td>';
            }
            if($y == 7){
                $y=0;
                echo '</tr><tr>';
            }
        }
        echo '</tr></tbody>';
    }
    echo '</table>';
}
?>
  • Which data is the variable $info has in function montaEventos? What error appears on the screen? Why use $row->{$titulo} and not $row->nome_da_coluna_do_db?

  • Hi Valdeir! I edited the question to insert in it the error print, which better directs the investigation of the problem. Sorry for the blunder.

1 answer

0


The error is because the index encontra in $info['encontro']. The variable $info in the method montaEventos does not bring a value.

To fix this, you must use a ternary operator.

It works as follows:

(expr1) ? value1 : value2;

He will compare the expr1, if it is true, returns value1, otherwise, returns value2

That one ternary is nothing more than a if..else is a single line.


To fix this error you must create a condition to check the content $info['encontro'] exists, if not, you can add a new value or return null.

Ex (PHP 7+): $encontro = $info['encontro'] ?? null;

Ex (PHP 5+): $encontro = isset($info['encontro']) ? $info['encontro'] : "valor qualquer";

Thus, when the index encontro nay exist in the variable $info, the variable $encontro will have the value of null.


The second mistake is because the query below, does not bring the column with the name being defined in the variable $encontro (because that variable does not receive a value).

"SELECT * FROM `".$tabela."`"

To correct this error, it is necessary to replace 'encontro' => $row->{$encontro} for:

'encontro' => ($encontro == null) ? "Valor qualquer" : $row->{$encontro}

You can also add a var_export($row); before $dataArr = date('Y-m-d', strtotime($row->{$data})); to verify what the query brings in the result.

  • Then I understood the problem! Thank you, Valdeir!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.