See if element exists in the php database

0

I'm trying that when the user leaves the focus of an input text it shows if that value already exists in the database or not, but it always throws at me that it exists. (The request goes through a controller but I omit it here), I feel that the error must be in the query to the database

Javascript code that sends the value using AJAX

$("#ordenTrabajo").blur(function() {
var orden = document.getElementById("ordenTrabajo").value;
if (!(orden == "")) {
    $.ajax({
        url: "views/ajax/OIT.php",
        method: "GET",
        data: { funcion: "funcion3", "or": orden },
        async: false,
        //dataType: "json",
        success: function(respuesta) {
            if (respuesta == "existe") {
                alert("Existe");
            } else {
                alert("No Existe");
            }
        }
    });
}

}); File php where the AJAX arrives

<?php

require_once "../../controllers/OIT.php";
require_once "../../models/OIT.php";


#CLASES
#**********************************************************************

class Ajax{


   #COMPROBAR SI ORDEN EXISTE
    #******************************************************************

    public $ordenTrabajo;

    public function comprobarOrden(){

       $datos = array("orderJob" => $this -> ordenTrabajo);
       $respuesta = GestorOIT::obtenerOrdenController($datos);
       echo $respuesta;

   }


#OBJETOS
#************************************************************************

//Comprobar que la dato no venga vacio
if(isset($_GET['funcion']) && !empty($_GET['funcion'])) {
    $funcion = $_GET['funcion'];

    //En función del parámetro que nos llegue ejecutamos una función u otra
    switch($funcion) {
        case 'funcion1': 
            $a = new Ajax();
            $a -> gestorViasAjax();
            break;
        case 'funcion2': 
           $b = new Ajax();
           $b -> gestorDestinosAjax();
            break;
        case 'funcion3': 
           $c = new Ajax();
           $c -> ordenTrabajo = $_GET["or"];
           $c -> comprobarOrden();
           break;
    }
}


?>

Model where the query runs

public function obtenerOrdenModel($datos, $tabla){
        $stmt = Conexion::conectar() -> prepare("SELECT n_lote FROM cajas WHERE ordenTrabajo=:orden");
         $stmt -> bindParam(":orden", $datos["orderJob"], PDO::PARAM_STR);
         $stmt->execute();
         $stmt -> fetch();
         if($stmt!=""){
            return "existe";
         }else{
            return "no";
         }
    
asked by Baker1562 15.02.2018 в 22:18
source

2 answers

1

I think the error is in this check:

$stmt -> fetch();
if($stmt!=""){
  return "existe";
}else{
  return "no";
}

Since $stmt is an object, I do not think it's best to compare it with an empty string. To know if you exist, you could do the following:

  $stmt = Conexion::conectar() -> prepare("SELECT 1 FROM cajas WHERE ordenTrabajo=:orden");
  $stmt -> bindParam(":orden", $datos["orderJob"], PDO::PARAM_STR);
  $stmt->execute();
  $count = $stmt->fetchColumn();
  if($count > 0){
      return "existe";
  }else{
      return "no";
  }

or directly

if(!$stmt->fetchColumn()){
    return "existe";
}else{
    return "no";
}

Notes, that I have changed the query for a 1, since you do not need more to know if it exists or not.

    
answered by 15.02.2018 / 22:38
source
0

In the end I managed to fix it changed this line

if($stmt!="")

for this

if($stmt->rowCount()>0)
    
answered by 15.02.2018 в 22:43