Calendar in PHP

Asked

Viewed 777 times

1

Does anyone know how I put one loop in that calendar, I just need it to print the dates registered in my bank.

Makes a mistake in query:

Warning: mysql_fetch_array() expects Parameter 1 to be Resource, Boolean Given in C: xampp htdocs Shamcey functions.php online 198

function MostreSemanas() {
    $semanas = "DSTQQSS";

    for( $i = 0; $i < 7; $i++ )
        echo "<td>".$semanas{$i}."</td>";

}

function GetNumeroDias( $mes ) {
    $numero_dias = array( 
        '01' => 31, '02' => 28, '03' => 31, '04' =>30, '05' => 31, '06' => 30,
        '07' => 31, '08' =>31, '09' => 30, '10' => 31, '11' => 30, '12' => 31
    );

    if (((date('Y') % 4) == 0 and (date('Y') % 100)!=0) or (date('Y') % 400)==0) {
        $numero_dias['02'] = 29;    // altera o numero de dias de fevereiro se o ano for bissexto
    }

    return $numero_dias[$mes];
}

function GetNomeMes( $mes ) {
    $meses = array( 
        '01' => "Janeiro", '02' => "Fevereiro", '03' => "Março",
        '04' => "Abril",   '05' => "Maio",      '06' => "Junho",
        '07' => "Julho",   '08' => "Agosto",    '09' => "Setembro",
        '10' => "Outubro", '11' => "Novembro",  '12' => "Dezembro"
    );

    if( $mes >= 01 && $mes <= 12)
        return $meses[$mes];

        return "Mês deconhecido";
}


function MostreCalendario( $mes  ) {

    $numero_dias = GetNumeroDias( $mes );   // retorna o número de dias que tem o mês desejado
    $nome_mes = GetNomeMes( $mes );
    $diacorrente = 0;   

    $diasemana = jddayofweek( cal_to_jd(CAL_GREGORIAN, $mes,"01",date('Y')) , 0 );  // função que descobre o dia da semana

    echo "\n<h4 class='widgettitle title-inverse'>".$nome_mes."</h4>";
    echo "\n<table>";
        echo "<tr>";
        MostreSemanas();    
        echo "</tr>";


    for( $linha = 0; $linha < 6; $linha++ ) {
        echo "<tr>";

        for( $coluna = 0; $coluna < 7; $coluna++ ) {
            echo "<td";

            if( ($diacorrente == ( date('d') - 1) && date('m') == $mes) ) {
                echo " id='dia_atual' ";
            }

            else {
                if(($diacorrente + 1) <= $numero_dias ) {

                    if( $coluna < $diasemana && $linha == 0) {
                        echo " id='dia_branco' ";
                    }
                    else {
                        echo " id='dia_comum'";
                    }
                }
                else {
                    echo " ";
                }
            }

            echo ">";

            /* TRECHO IMPORTANTE: A PARTIR DESTE TRECHO É MOSTRADO UM DIA DO CALENDÁRIO (MUITA ATENÇÃO NA HORA DA MANUTENÇÃO) */
            if( $diacorrente + 1 <= $numero_dias ) {

                if( $coluna < $diasemana && $linha == 0) {
                    echo " ";
                }
                else {
                    //echo "<input type = 'button' id = 'dia_comum' name = 'dia".($diacorrente+1)."'  value = '".++$diacorrente."' onclick = \"acao(this.value)\">";
                    $query = mysql_query("SELECT data FROM _atendimento_medico WHERE date_format(data, '%m') = '$mes'");
                    while($resposta = mysql_fetch_array($query)) {

                    if($diacorrente == ( date( 'd', strtotime( $resposta['data']) && date( 'm', strtotime( $resposta['data'] == $mes) ) ) )) {
                        echo "<a href ='". getURL(array('calendar')) ."&mes=$mes&dia=".($diacorrente+1)."' class='consulta'>".++$diacorrente . "</a>";
                    }
                    else {
                        echo "<a href ='". getURL(array('calendar')) ."&mes=$mes&dia=".($diacorrente+1)."'>".++$diacorrente . "</a>";}
                }




                }
            }
            else {
                break;
            }
            /* FIM DO TRECHO MUITO IMPORTANTE */

            echo "</td>";
        }
        echo "</tr>";
    }
    echo "</table>";
}

function MostreCalendarioCompleto() {
    echo "<ul id='slidercontent' class='calendar-consulta'>";
        echo "<li>";
        echo "<div class='slide_wrap'>";
        echo "<div class='slide_content'>";
            MostreCalendario(date('m'));
        echo "</div>";
        echo "</div>";
        echo "</li>";

    $cont = 1;
    for( $j = 0; $j < 4; $j++ ) {
        for( $i = 0; $i < 3; $i++ ) {

            echo "<li>";
            echo "<div class='slide_wrap'>";
            echo "<div class='slide_content'>";
                MostreCalendario( ($cont < 10 ) ? "0".$cont : $cont );  

            $cont++;
            echo "</div>";
            echo "</div>";
            echo "</li>";

        }
    }
    echo "</ul>";
}
  • Where is the SQL of your query and how you want to print it on the site?

  • Try to explain better what you want there, I look at the code and I can not understand what you want to print there on the 20th of the month 12.

  • I would like it to create a class='query' from the dates registered in the database. ex: when the date 01/01/2015 is registered in BD the date turned red in my system, I edited my code to you better understand, Thanks for the help

  • My query of error

  • 1

    The mistake I noticed was that a comma was missing here: date_format(data '%m'). If it’s not edit and add the error message in the question.

  • Thanks for the help, I added the error to the question and corrected the comma

  • From the error it seems mysql_query is returning false. What message mysql_error() returns?

  • Returns, IN DATABASE SELECTED

  • Strange because my connection to the comic is working.

  • Use the mysql_error function to get an idea of the problem. More at that link

Show 5 more comments

3 answers

2

The error obtained is realizing that the function mysql_fetch_array() expects an appeal but received a boleano:

Warning: mysql_fetch_array() expects Parameter 1 to be Resource, Boolean Given in C: xampp htdocs Shamcey functions.php on line 198

In short, this happens when the function mysql_query() failed, having returned FALSE, as we can read in the documentation:

For SELECT, SHOW, DESCRIBE or EXPLAIN commands, mysql_query() returns a Resource if successful, or FALSE if failed.

For other types of SQL queries, UPDATE, DELETE, DROP, etc., mysql_query() returns TRUE in case of success or FALSE in case of error.

Solution

What you should do is check the success of the query before trying to use data from it. This way you have access to the error and can act accordingly to resolve it:

// Ligação
$dbConn = mysql_connect("localhost", "mysql_user", "mysql_password");

// Selecionar Base de dados
mysql_select_db("minhaBaseDados", $dbConn);

// Consulta
$query = "
SELECT data
FROM _atendimento_medico
WHERE date_format(data, '%m') = '$mes'";

// Consultar a base de dados
$result = mysql_query($query);

// Verificar se obtivemos um erro
if ($result === false) {
    die(mysql_errno($dbConn) . ": " . mysql_error($dbConn) . "\n");
}

// Continuar com o trabalho
while($resposta = mysql_fetch_array($result)) {
    // ...
}

0

I am using this same calendar algorithm with small adaptations, follow the excerpt where I list the Events (records in the database) in the calendar, remembering that this excerpt is within the generation loop of the columns:

$dataCalendario = formataDia($diacorrente+1)."/".$mes."/".$ano;

                    # PESQUISANDO SE O USUÁRIO TEM ALGUM EVENTO CADASTRADO EM DETERMINADA DATA
                    $pdo2 = Connection::Conexao();
                    $sql2 = "SELECT * FROM EVENTOS as evt WHERE evt.USUARIOS_idUSUARIO=".$id." AND evt.DATA='".$dataCalendario."'";
                    $query2 = $pdo2->prepare($sql2);
                    $query2->execute();

                    # SE HOUVER EVENTO NO BANCO NA DATA, MOSTRA DESCRIÇÃO DO EVENTO NA RESPSCTIVA DATA
                    if( $query2->rowCount() > 0) { 

                        echo "<a href=../views/templateEvento.php?user=".$id."&d=".($diacorrente+1)."&m=".$mes."&a=".$ano.">".++$diacorrente.'</a>';

                        # PEGANDO TODOS OS EVENTOS ENCONTRADOS PARA A DATA E LISTA NO CALENDÁRIO
                        while($reg = $query2->fetch(PDO::FETCH_ASSOC)) { 

                            $descArray = array($reg["idEVENTO"] => $reg["TITULO"]);

                            foreach ($descArray as $value) {
                                echo "<br /> <a class=evento >".$value."</a>";
                            }
                        }     

                    } else { 

                        echo "<a href=../views/templateEvento.php?user=".$id."&d=".($diacorrente+1)."&m=".$mes."&a=".$ano.">".++$diacorrente.'</a>';
                    } 

unset($descArray);
unset($pdo2);
unset($query2);
$sql2="";

0

I think your mistake is in the consultation:

$query = mysql_query("SELECT data FROM _atendimento_medico 
                      WHERE date_format(data, '%m') = '$mes'");

You are using a function following where date_format(data, '%m') instead of the name of the field/column where you want to make the query.

Browser other questions tagged

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