What's wrong with this query?

0

Right, I'm trying to do a select in a database via ajax using jQuery. Here are some excerpts from the code I'm using and more explanations:

Ajax function

function carregaRegistros(dia, mes, ano) {

    dia = parseInt(dia);
    mes = parseInt(mes);
    ano = parseInt(ano);

    $.ajax({
        method: "POST",
        url: "PHP-Files/carregaRegistros.php",
        data: {dia: dia, mes: mes, ano: ano},
        success: function(result){
            alert(result);
        }
    });
}

Query

// Cria conexão
$conn = new mysqli($servername, $username, $password, $dbname);
// Verifica conexão
if ($conn->connect_error) {
    die("Erro de conexão: " . $conn->connect_error);
}

$dia = $_POST["dia"];
$mes = $_POST["mes"];
$ano = $_POST["ano"];

$sql = "SELECT Cliente, TotalDeHoras, HoraDeEntrada, HoraDeSaida FROM 
apontamentos WHERE Dia='$dia' AND Mes='$mes' AND Ano='$ano'";

if ($conn->query($sql) === TRUE) {
    echo "Apontamento incluído com sucesso!";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

I have already checked and the connection is being made and the data is being passed correctly, however I get a return error message indicating that the select is not being done. I do not understand why this is happening and I'm a bit new to this part of creating database connections. If I have omitted any important information please ask for comments

    
asked by anonymous 01.06.2018 / 20:39

2 answers

1

A select query will not return a true, as in this comparison you are trying to make. You can even check if it will not return errors, but this comparison you are doing will never go into if. That's why your error does not return any errors, because there are no errors ... you can try to do so:

if ($conn->query($sql)) {}

I believe your question is supposing.

    
01.06.2018 / 20:54
1

The correct thing is to check for a record

  

The select count checks the number of nonzero lines within the count you want to do!

  $result = $conn->query("SELECT COUNT(*) FROM apontamentos WHERE Dia='$dia' AND Mes='$mes' AND Ano='$ano''");

  $row = $result->fetch_row();

  if ($row[0] > 0) {
      echo "Apontamento incluído com sucesso!";
  } else {
      echo "Error: " . $sql . "<br>" . $conn->error;
  }

or

$result = $conn->query("SUA QUERY")); 
if($result->num_rows){
   // echo "Apontamento incluído com sucesso!";
}else{
   // echo "Error: " . $sql . "<br>" . $conn->error;
}

To return the records

$result = $conn->query("SUA QUERY")); 
if($result->num_rows){

   while($row = $result->fetch_assoc()) {
        $Cliente = $row["Cliente"];
        $TotalDeHoras = $row["TotalDeHoras"];
        $HoraDeEntrada = $row["HoraDeEntrada"];
        $HoraDeSaida = $row["HoraDeSaida"];

     }

   // echo "Apontamento incluído com sucesso!";
}else{
   // echo "Error: " . $sql . "<br>" . $conn->error;
}
    
01.06.2018 / 21:18