How to check if a select is null

1

People, I have this code that pulls server info

try {
    $conecta  = new PDO("mysql:host=$servidor;dbname=$banco", $usuario, $senha);
    $consulta = $conecta->prepare('SELECT * FROM tb02_cardapiosem WHERE tb02_diasemana=' . $data);
    $consulta->execute(array());
    $resultadoDaConsulta = $consulta->fetchAll();

    $StringJson = "[";

    if (count($resultadoDaConsulta)) {
        foreach ($resultadoDaConsulta as $registro) {

            if ($StringJson != "[") {
                $StringJson .= ",";
            }
            $StringJson .= '{"tb02_lanchedia":"' . $registro[tb02_lanchedia] . '",';
            $StringJson .= '"tb02_almoco":"' . $registro[tb02_almoco] . '",';
            $StringJson .= '"tb02_cafe":"' . $registro[tb02_cafe] . '",';
            $StringJson .= '"tb02_lanchenoite":"' . $registro[tb02_lanchenoite] . '",';
            $StringJson .= '"tb02_diasemana":"' . $registro[tb02_diasemana] . '"}';

        }
        echo $StringJson . "]"; // Exibe o vettor JSON
    }   
}   
catch (PDOException $e) {
    echo 'ERROR: ' . $e->getMessage(); // opcional, apenas para teste
}

Then I have this code that plays the information found in a div

function ConectaServidor(response) {
    var dados = JSON.parse(response); //faz a conversão do texto da WEB para JSON
    var i;
    var conteudo = "";
    var conteudo2 = "";
    var conteudo3 = "";
    var conteudo4 = "";
    for (i = 0; i < dados.length; i++) //dados.length retorna o tamanho do vetor.
    {
        conteudo += dados[i].tb02_cafe;
        conteudo2 += dados[i].tb02_lanchedia;
        conteudo3 += dados[i].tb02_almoco;
        conteudo4 += dados[i].tb02_lanchenoite;
    }

    document.getElementById("cafe1").innerHTML = conteudo;
    document.getElementById("lanche1").innerHTML = conteudo2;
    document.getElementById("almoco1").innerHTML = conteudo3;
    document.getElementById("lanchen1").innerHTML = conteudo4;
}

However, it is not all the dates that are registered and I would like it when a date was not found, it would put the div's innerHTML as "There is no record!". How to do?

    
asked by anonymous 12.10.2017 / 15:00

3 answers

0

Folks, I settled on a simple else. Look and compare with the previous code:

    try {
$conecta  = new PDO("mysql:host=$servidor;dbname=$banco", $usuario, $senha);
$consulta = $conecta->prepare('SELECT * FROM tb02_cardapiosem WHERE tb02_diasemana=' . $data);
$consulta->execute(array());
$resultadoDaConsulta = $consulta->fetchAll();

$StringJson = "[";

if (count($resultadoDaConsulta)) {
    foreach ($resultadoDaConsulta as $registro) {

        if ($StringJson != "[") {
            $StringJson .= ",";
        }
        $StringJson .= '{"tb02_lanchedia":"' . $registro[tb02_lanchedia] . '",';
        $StringJson .= '"tb02_almoco":"' . $registro[tb02_almoco] . '",';
        $StringJson .= '"tb02_cafe":"' . $registro[tb02_cafe] . '",';
        $StringJson .= '"tb02_lanchenoite":"' . $registro[tb02_lanchenoite] . '",';
        $StringJson .= '"tb02_diasemana":"' . $registro[tb02_diasemana] . '"}';

    }
    echo $StringJson . "]"; // Exibe o vettor JSON
}else{
        echo $StringJson = '["Não há dados!"]';
    }
}       
   catch (PDOException $e) {
       echo 'ERROR: ' . $e->getMessage(); // opcional, apenas para teste
     }

There in my javascript:

    function ConectaServidor(response) {
    var dados = JSON.parse(response);
    if(dados=="Não há dados!"){
        document.getElementById("cafe1").innerHTML = dados;
        document.getElementById("lanche1").innerHTML = dados;
        document.getElementById("almoco1").innerHTML = dados;
        document.getElementById("lanchen1").innerHTML = dados;
    }else{
    var i;
    var conteudo = "";
    var conteudo2 = "";
    var conteudo3 = "";
    var conteudo4 = "";
    for (i = 0; i < dados.length; i++) //dados.length retorna o tamanho do vetor.
    {
        conteudo += dados[i].tb02_cafe;
        conteudo2 += dados[i].tb02_lanchedia;
        conteudo3 += dados[i].tb02_almoco;
        conteudo4 += dados[i].tb02_lanchenoite;
    }

    document.getElementById("cafe1").innerHTML = conteudo;
    document.getElementById("lanche1").innerHTML = conteudo2;
    document.getElementById("almoco1").innerHTML = conteudo3;
    document.getElementById("lanchen1").innerHTML = conteudo4;
    }}}

Anyway, thanks to everyone! ;)

    
15.10.2017 / 01:00
1

Good morning!

First, I suggest using a Javascript library like Jquery , for example. I think it's really going to make it easier for you to work on the front end and how you're going to handle the data.

The second point in my opinion that should be improved is the way you are treating the data in the backend. It would be much simpler and more correct for you to return the result of your SQL query and convert it to a real json format (not assembling a String) using the json_encode () function that is native to PHP.

Answering your question, come on. On the front end, when you receive the data and manipulate it it seems a little confusing because the snacks are all concatenated in a single variable that will then be displayed in an HTML element. I believe that each of these values should be attributed to a list, for example, it would make more sense. So the only thing you should do to assign the desired content to dates that have no value would be something of the sort:

conteudoX = (dados[i].tb02_dia_semana) ? dados[i].tb02_dia_semana: 'Data não informada';

After this conditional execution, your conteudoX variable will have the expected value and this way you can assign it to the element you want in HTML.

I hope I have helped:)

Hugs!

    
12.10.2017 / 16:13
0

You can use the SQL query itself to return "There is no record!" as a field value, if it is null in tb02 , using coalesce() . This function returns the first non-null value found in the list:

SELECT 
    tb02_diasemana,
    coalesce(tb02_lanchedia,   'Não há registro!') as tb02_lanchedia,
    coalesce(tb02_almoco,      'Não há registro!') as tb02_almoco,
    coalesce(tb02_cafe,        'Não há registro!') as tb02_cafe,
    coalesce(tb02_lanchenoite, 'Não há registro!') as tb02_lanchenoite
FROM tb02_cardapiosem 
WHERE tb02_diasemana=' . $data

The advantage is that the rest of your code does not change. Breaking avoids the use of select * , which can cause you headaches in the future if new columns are added to the table.

    
12.10.2017 / 17:19