Run two sql queries in the same function

0

I am trying to get the emails from two different tables, in order to gather them in a single array to send mass messages to all subscribers.

I do not know if I can do it this way but what I did in the controller was send the name of two tables to the model like this:

static public function mensajesMasivosController(){

        if(isset($_POST["tituloMasivoEs"])){

            $respuesta =  MensajesModelEs::seleccionarEmailSuscriptores("suscriptorespanol");

            $respuesta .= MensajesModelEs::seleccionarEmailSuscriptores("suscriptorform");


        }
    }

Now this I put in the model

static public function seleccionarEmailSuscriptores($tabla){

    $stmt = Conexion::conectar()->prepare("SELECT email FROM $tabla");

    $stmt .= Conexion::conectar()->prepare("SELECT email FROM $tabla");
    $stmt->execute();
    return $stmt -> fetchAll();

    $stmt -> close();


}

Now I get this error:

Recoverable fatal error: Object of class PDOStatement could not be converted to string

What could I do to select info from two tables at the same time?

Thanks for your reply

    
asked by J P 27.11.2018 в 06:31
source

1 answer

0

Obviously not. The . is to concatenate string not to join arrays. To achieve what disaster you have 2 options from my point of view, use UNION SQL% or make a merge of the results with array_merge ().

Example UNION, you pass the 2 names of the table to the function:

static public function seleccionarEmailSuscriptores($tabla, $tabla2)
{
    $stmt = Conexion::conectar()->prepare("SELECT email FROM $tabla UNION SELECT email FROM $tabla2");

    $stmt->execute();
    return $stmt -> fetchAll();
}

When calling the method:

$respuesta =  MensajesModelEs::seleccionarEmailSuscriptores("suscriptorespanol", "suscriptorform");

Example with array_merge ()

In the method you only need to ask a question:

static public function seleccionarEmailSuscriptores($tabla)
{
    $stmt = Conexion::conectar()->prepare("SELECT email FROM $tabla");

    $stmt->execute();
    return $stmt -> fetchAll();
}

When calling the method:

$respuesta =  MensajesModelEs::seleccionarEmailSuscriptores("suscriptorespanol");
$respuesta2 =  MensajesModelEs::seleccionarEmailSuscriptores("suscriptorform");
// unimos los resultados 
$result = array_merge($respuesta, $respuesta2);
    
answered by 27.11.2018 / 11:46
source