I do not receive values from SELECT FROM but from INSERT INTO and if the record exists (MVC, PDO, MYSQL)

1

Hi, I'm working with PHP and MySql with PDO and the model view controller (MVC) but I have an error when trying to do a SELECT * on the model side. My intrigue is that it works when I do INSERT INTO and when it's a SELECT. what I do is a validation of the existence of a record in the database and I apply rowCount () to know if it was successfully brought up and equal to 1 but always arrives 0 but the record does exist in the database

$datosUs=[
            "clave_usuario"=>$usuario,
            "contrasenia"=>$contrasenia
        ];

        $datosCuenta=loginModelo::iniciar_sesion_modelo($datosUs);


        if($datosCuenta->rowCount()==1){
            $row = $datosCuenta->fetchAll();

and this sends it to the model

protected function iniciar_sesion_modelo($datos){
        $sql=mainModel::conectarBD()->prepare("SELECT * FROM usuarios WHERE clave_usuario='RIVE' AND contraseña='123456' AND estatus=true");

        $sql->bindParam(":clave",$datos['clave_usuario']);
        $sql->bindParam(":contrasenia",$datos['contrasenia']);

        $sql->execute();

        return $sql;
    }

my PDO function that calls the model

protected function conectarBD(){

        $cadenaconexion = new PDO(SGBD,USER,PASS);

        return $cadenaconexion;
    }

**

-------------- ABOVE DOES NOT BRING ME A VALUE |

-------------- DOWN IF YOU BRING ME VALUES |

**

  

In my query, I do not use the bindParam, I just give it a value by assigning variables

$buscar_servicio=mainModel::consultas_simples("SELECT * FROM servicios WHERE clave_servicio='$clave_servicio'");
  

mainModel

**protected function conectarBD(){

        $cadenaconexion = new PDO(SGBD,USER,PASS);

        return $cadenaconexion;
    }
    //ejecucion de consultas simples para agilizar codigo
    protected function consultas_simples($consulta){
        $respuesta = self::conectarBD()->prepare($consulta);
        $respuesta->execute();

        return $respuesta;
    }
  

when I make an insert

$guardar=servicioModelo::agregar_servicio_modelo($datos);

            if($guardar->rowCount()>=1){

                $alerta=[
                "Alerta"=>"limpiar",
                "Titulo"=>"¡Listo!",
                "Texto"=>"El servicio se ah agreagado con exito.",
                "Tipo"=>"success" 
            ];
            return mainModel::sweet_alert($alerta);
            }else{

                $alerta=[
                "Alerta"=>"simple",
                "Titulo"=>"Atención",
                "Texto"=>"No se pudo agregar el servicio./nIntentelo nuevamente.",
                "Tipo"=>"error" 
            ];
            return mainModel::sweet_alert($alerta);
            }
  

model

protected function agregar_servicio_modelo($datos){
        $sql=mainModel::conectarBD()->prepare("INSERT INTO servicios(clave_servicio,servicio,descripcion) VALUES(:clave,:servicio,:descripcion)");

        $sql->bindParam(":clave",$datos['clave_servicio']);
        $sql->bindParam(":servicio",$datos['servicio']);
        $sql->bindParam(":descripcion",$datos['descripcion']);

        $sql->execute();

        return $sql;
    }   
    
asked by Rodrigo Isaac Vera Euan 04.07.2018 в 18:39
source

1 answer

0

Up does not bring you values because the query fails. If there are no bookmarks in the query you can not use bindParam and in that case you should not use prepare / execute but query .

If you write your code above like this, it should work:

protected function iniciar_sesion_modelo($datos){
        $sql=mainModel::conectarBD()->query("SELECT * FROM usuarios WHERE clave_usuario='RIVE' AND contraseña='123456' AND estatus=true");
        return $sql;
    }

As for the other query, you should properly apply the prepared queries criterion, which is very simple.

For example, you can pass two parameters to consultas_simples , one would be the query to prepare, and the other the data:

/*
    *Nótese que ahora la función recibe otro parámetro 
    *llamado $arrParams, el cual servirá para pasar los datos
    *y enviarlos al manejador a través del método execute
*/
protected function consultas_simples($consulta,$arrParams){
    $respuesta = self::conectarBD()->prepare($consulta);
    $respuesta->execute($arrParams); //PDO permite pasar los valores en el execute y esto es magnífico
    return $respuesta;
}

To call her, you would do this:

$strSQL="SELECT * FROM servicios WHERE clave_servicio=?";
$arrParams=array($clave_servicio);
$buscar_servicio=mainModel::consultas_simples($strSQL,$arrParams);

What we have done has been:

  • Put a placeholder in the query ?
  • To pass in $arrParams the values and in the function we take advantage of the fact that PDO allows us to pass the parameters that would eventually be passed in bindParam , like an array in execute .

Suppose you want to send a prepared query to consultas_simples with more parameters:

$strSQL="SELECT * FROM servicios WHERE clave_servicio=? AND nombre=? WHERE id>?";
$arrParams=array($clave_servicio,$nombre,$id);
$buscar_servicio=mainModel::consultas_simples($strSQL,$arrParams);

The trick is to write your query well, with its markers, what you need, and put in the array each value corresponding to the values of each marker. You pass the data to consultas_simples and PDO does the rest.

I hope it serves you and if there are doubts, you can manifest it in comments.

    
answered by 04.07.2018 / 19:04
source