How to perform a bind_param() with SELECT UNION ALL

Asked

Viewed 64 times

-1

I have that code.

<?php
$link = new mysqli("localhost","root", "SENHAAAA", "BANCO");
$sql_saldo_total = $link->prepare(
   "SELECT sum(g) saldo_total 
      FROM ( SELECT SUM(valor_pg) g 
         FROM tabela1 
         WHERE departamento = ? 
         AND MONTH(data_pg) <= ? 
         AND YEAR(data_pg) = ? 
         AND
         UNION ALL
         SELECT SUM(valor) 
         FROM tabela2 
         WHERE tipo = ? 
         AND MONTH(data) <= ? 
         AND YEAR(data) = ?
      ) tabela_virtual");

$sql_saldo_total->bind_param("siisii",
$departamento, 
$mes, 
$ano, 
$departamento, 
$mes, 
$ano);
?>

But he’s returning the error:

Fatal error: Call to a member function bind_param() on a non-object in 
  • Yes. It really was a distraction. I left him in the middle disturbing my service. Thank you!!!!!

  • Yes yes. Thank you!!!

1 answer

3

Your problem is that in your SQL in part:

AND YEAR(data_pg) = ? AND UNION ALL

There is a AND before UNION ALL and therefore generates error. Because there was a failure to prepare SQL.

A good practice is to test each step. Checking for possible errors and this makes it easier to locate the problem.

Follows the solution in SQL and improvement in source code:

<?php
    $link = new mysqli("localhost","root", "SENHAAAA", "BANCO");
    if ($link->connect_errno) {
         die ("Falha ao conectar ao MySQL: (" . $link->connect_errno . ") " . 
               $link->connect_error);
   }

    $sql_saldo_total = $link->prepare(
            "SELECT sum(g) saldo_total 
               FROM ( SELECT SUM(valor_pg) g 
                        FROM tabela1 
                       WHERE departamento = ? 
                         AND MONTH(data_pg) <= ? 
                         AND YEAR(data_pg) = ? 
                       UNION ALL
                      SELECT SUM(valor) 
                        FROM tabela2 
                       WHERE tipo = ? 
                         AND MONTH(data) <= ? 
                         AND YEAR(data) = ?
                    ) tabela_virtual");

     if (!$sql_saldo_total) {
        die("Falha ao preparar o SQL: (" . $link->errno . ") " . $link->error);
     }

     if (!$sql_saldo_total->bind_param("siisii",
                                  $departamento, 
                                  $mes, 
                                  $ano, 
                                  $departamento, 
                                  $mes, 
                                  $ano)) {
         die ("Falha ao associar os parâmetros: (" . $sql_saldo_total->errno . ") " . 
               $sql_saldo_total->error);
     }
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.