SQLSRV Null value will be deleted by Aggregate or Set - php

i trie to execute a Stored Procedure from PHP. My other SP´s are working correctly. But this one will make problems.
Here is my code for calling the SP:
$sqlStmt = "EXEC MOBILE_CSKLIENT_LoadForSync #pCEGERAETNR = ?";
$con = DatabaseManager::GetDatabaseConnection($serial);
$deviceNr = $this->GetDeviceNr($serial, $deviceId);
$res = sqlsrv_query($con, $sqlStmt, array($deviceNr));
if($res == false)
{
die( print_r( sqlsrv_errors(), true));
}
else
{
die( print_r( sqlsrv_errors(), true));
$result = array();
while($zeile = sqlsrv_fetch($res))
{
echo sqlsrv_get_field($res, 0);
}
}
here is my SP:
GO
/****** Object: StoredProcedure [dbo].[MOBILE_CSKLIENT_LoadForSync] Script Date: 25.02.2014 08:36:01 ******/
ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MOBILE_CSKLIENT_LoadForSync](#pCEGERAETNR FLOAT)
AS
BEGIN
DECLARE #pLASTCHANGE datetime
SET #pLASTCHANGE = (SELECT MAX(LASTCHANGE) FROM CEMITARB WHERE CEGERAETNR = #pCEGERAETNR)
IF #pLASTCHANGE IS NULL
BEGIN
SELECT K.KLIENTNR, K.PROGRAMMNR, K.NAME,
K.VORNAME, K.[STR], K.PLZ, K.ORT , K.TELEFON1, K.TELEFON2, K.GEBDAT, K.GESCHLECHT, K.KEYKLIFR1, K.MAINVERSION
FROM CSKLIENT K
INNER JOIN S1PAT P ON P.KLIENTNR = K.KLIENTNR
INNER JOIN CSKLIZR Z ON Z.KLIENTNR = K.KLIENTNR
WHERE P.AKTIV = 'J'
AND (Z.AUFNAHME IS NULL OR Z.AUFNAHME <= GetDate())
AND (Z.ENTLASSUNG IS NULL OR Z.ENTLASSUNG >= GetDate())
UNION
SELECT K.KLIENTNR, K.PROGRAMMNR, K.NAME,
K.VORNAME, K.[STR], K.PLZ, K.ORT , K.TELEFON1, K.TELEFON2, K.GEBDAT, K.GESCHLECHT, K.KEYKLIFR1, K.MAINVERSION
FROM CSKLIENT K
INNER JOIN H1BEW B ON B.KLIENTNR = K.KLIENTNR
WHERE B.AKTIV = 'J' AND ZIMMER IS NOT NULL AND BEREICH IS NOT NULL
END
ELSE
BEGIN
SELECT K.KLIENTNR, K.PROGRAMMNR, K.NAME,
K.VORNAME, K.[STR], K.PLZ, K.ORT , K.TELEFON1, K.TELEFON2, K.GEBDAT, K.GESCHLECHT, K.KEYKLIFR1, K.MAINVERSION
FROM CSKLIENT K
INNER JOIN S1PAT P ON P.KLIENTNR = K.KLIENTNR
INNER JOIN CSKLIZR Z ON Z.KLIENTNR = K.KLIENTNR
WHERE P.AKTIV = 'J' AND K.LASTCHANGE >= #pLASTCHANGE
AND (Z.AUFNAHME IS NULL OR Z.AUFNAHME <= GetDate())
AND (Z.ENTLASSUNG IS NULL OR Z.ENTLASSUNG >= GetDate())
UNION
SELECT K.KLIENTNR, K.PROGRAMMNR, K.NAME,
K.VORNAME, K.[STR], K.PLZ, K.ORT , K.TELEFON1, K.TELEFON2, K.GEBDAT, K.GESCHLECHT, K.KEYKLIFR1, K.MAINVERSION
FROM CSKLIENT K
INNER JOIN H1BEW B ON B.KLIENTNR = K.KLIENTNR
WHERE B.AKTIV = 'J' AND ZIMMER IS NOT NULL AND BEREICH IS NOT NULL
AND K.LASTCHANGE >= #pLASTCHANGE
END
END
So i now get the Error:
Error: [Microsoft][SQL Server Native Client 10.0][SQL Server]Warnung: Ein NULL-Wert wird durch einen Aggregat- oder sonstigen SET-Vorgang gel\224scht.
Translatet to English:
A Null value will be delete by a aggregat or a set action
My Procedure works fine if i execute it from the SQL Management Studio.
The Procedure should return 222 rows.
I tried to set:
sqlsrv_configure("WarningsReturnAsErrors", 0);
But then nothing was returned from the Procedure.

i found the solution:
the problem was this line in my SP:
SET #pLASTCHANGE = (SELECT MAX(LASTCHANGE) FROM CEMITARB WHERE CEGERAETNR = #pCEGERAETNR)
LastChange can be Null and this was the problem.
So i changed the code to:
IF((SELECT DISTICT LASTCHANGE FROM CEMITARB WHERE CEGERAETNR = #pCEGERAETNR) IS NULL)
BEGIN
SET #pLASTCHANGE = NULL
END
ELSE
BEGIN
SET #pLASTCHANGE = (SELECT MAX(LASTCHANGE) FROM CEMITARB WHERE CEGERAETNR = #pCEGERAETNR)
END
Now my code executes fine. And sqlsrv_query returns the correct items.

Related

Stored Procedure didn't execute all the data

I got a problem while executing my stored procedure in web service that I create in PHP language. If I execute the SP below directly in SQL Server Management Studio, it works perfectly. But when I execute the SP from my web service with PHP, it only executes some of the data in the looping I made in SP.
I got a service table as a master room data. In that SP below, I would like to check is the room available in a date range that I input to stored procedure one by one.
For example, I got 6 rooms in service table, and I want to check it one by one in looping with cursor. When I execute the SP in web service, it only execute 4 rooms in looping, but if I execute the SP in management studio directly, it works perfectly.
Can somebody help me to solve this problem?
Thank you.
Create Procedure GetAvailableRoom
#Date1 Datetime,
#Date2 Datetime,
#UserID Varchar(15)
AS
Begin
Delete From Room_Availability Where UserID = #UserID
Declare #KL Varchar(50)
Declare Cursor_RA Cursor For SELECT Service_Code FROM Services Where Status = 'ROOM' Order By Service_Code
Open Cursor_RA
Fetch Next From Cursor_RA Into #KL
While ##FETCH_STATUS = 0
Begin
print #KL
Declare #MyDate DateTime
Set #MyDate = #Date1
Declare #Diff Int
Set #Diff = DateDiff(Day, #Date1, #Date2)
Declare #Counter Int
Set #Counter = 0
print #MyDate
print #Diff
print #Counter
While (#Counter <= #Diff)
Begin
Print 'My Date is ' + Convert(Varchar, format(#MyDate,'yyyy-MM-dd'))
if exists(SELECT #KL, format(#MyDate,'yyyy-MM-dd 00:0:00'), Customers.Name + ' | ' + Customers.HP, #UserID
FROM Reservation INNER JOIN Reservation_Details ON Reservation.Reservation_Code = Reservation_Details.Reservation_Code
INNER JOIN Customers ON Reservation.Customer_ID = Customers.Customer_ID
WHERE Reservation_Details.Kode_Service = #KL AND
Reservation_Details.Checkin <= format(#MyDate,'yyyy-MM-dd 23:59:59') AND
Reservation_Details.Checkout >= format(#MyDate,'yyyy-MM-dd 00:0:00'))
Begin
print 'exists'
Insert Into Room_Availability (Service_Code,Service_Date,Customer,UserID)
SELECT #KL, format(#MyDate,'yyyy-MM-dd 00:0:00'), Customers.Name + ' | ' + Customers.HP, #UserID
FROM Reservation INNER JOIN Reservation_Details ON Reservation.Reservation_Code = Reservation_Details.Reservation_Code
INNER JOIN Customers ON Reservation.Customer_ID = Customers.Customer_ID
WHERE Reservation_Details.Service_Code = #KL AND
Reservation_Details.Checkin <= format(#MyDate,'yyyy-MM-dd 23:59:59') AND
Reservation_Details.Checkout >= format(#MyDate,'yyyy-MM-dd 00:0:00')
End
Else
Begin
print 'not exists'
Insert Into Room_Availability (Service_Code,Service_Date,Customer,UserID)
Values(#KL, format(#MyDate,'yyyy-MM-dd 00:0:00'), 'EMPTY', #UserID)
End
Set #MyDate = dateadd(dd,1,#MyDate)
Set #Counter = #Counter + 1
End
Fetch Next From Cursor_RA Into #KL
End
Close Cursor_RA
Deallocate Cursor_RA
End
This is the web service code.
<?php
include 'settings.php';
ini_set('mssql.connect_timeout',15);
$sqlconn = sqlsrv_connect($serverName, $connectionOptions);
if ($sqlconn === false)
die(FormatErrors(sqlsrv_errors()));
$tsql = "GetAvailableRoom '" . $_POST['Date1'] . "','" . $_POST['Date2'] . "','" . $_POST['UserID'] . "'";
//echo $tsql;
$cursorType = array("Scrollable" => SQLSRV_CURSOR_DYNAMIC);
$getexec = sqlsrv_query($sqlconn, $tsql, null, $cursorType);
if ($getexec === false)
die(FormatErrors(sqlsrv_errors()));
sqlsrv_free_stmt($getexec);
sqlsrv_close($sqlconn);

SQL Takes too much

For some reason my script takes too much time, that is why i had to add the ini_set('max_execution_time', 300); since 30 seconds being the default got me a fatal error.
I can't understand why this is happening, if i go directly into SSMS i get that query in 0 secs. what can be happening? i am running wamp with php 5.4.16 and the extension php_sqlsrv_54_ts
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
ini_set('max_execution_time', 300);
include "ChromePhp.php";
$sort = isset($_POST['sort']) ? strval($_POST['sort']) : 'Cliente';
$order = isset($_POST['order']) ? strval($_POST['order']) : 'DESC';
include "includes/db_config.php";
$conn = sqlsrv_connect(SV_NAME, $connectionInfo) OR die("Unable to connect to the database");
$sql =
"SELECT * FROM
(Select
Id
,Cliente
,Contrato
,Anexo
,SO
,NombreFlota
,(SELECT count(*) FROM LiveTest LEFT JOIN Producto ON Producto.Id=LiveTest.Producto_Id WHERE Producto.Order_Id=Orders.Id) as Hechas
,((SELECT count(*) FROM Producto WHERE Order_Id=Orders.Id) - (SELECT count(*) FROM LiveTest LEFT JOIN Producto ON Producto.Id=LiveTest.Producto_Id WHERE Producto.Order_Id=Orders.Id and RMA is null )) as Pendientes
,(SELECT count(*) FROM Producto WHERE Order_Id=Orders.Id ) as Total
FROM
Orders
WHERE
Orders.FechaPick is not null) as A
WHERE Total - Pendientes >0
ORDER BY $sort $order";
ChromePHP::log($sql);
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$result = array();
$res = sqlsrv_query($conn, $sql, $params, $options);
while($row = sqlsrv_fetch_object($res))
{
array_push($result, $row);
}
ChromePHP::log($result);
echo json_encode($result);
?>
try to modify your query like this:
Note : you do 'where f0b.Order_Id=f1.Id' then your left ouer join is cancelled because you test a value (that's why i have replaced by inner join), if you want null value too, you must do it : 'where f0b.Order_Id=f1.Id or f0b.Order_Id is null'
Select
Id
,Cliente
,Contrato
,Anexo
,SO
,NombreFlota
,isnull(f3.NbProdLive, 0) as Hechas
,isnull(f2.NbProd, 0) - isnull(f3.NbProdLiveRMANull, 0) as Pendientes
,isnull(f2.NbProd, 0) as Total
FROM
Orders f1
outer apply
(
select count(*) NbProd from Producto f0
where f0.Order_Id=f1.Id
) f2
outer apply
(
select count(*) NbProdLive, sum(case when RMA is null then 1 else 0 end) NbProdLiveRMANull
from LiveTest f0 INNER JOIN Producto f0b ON f0b.Id=f0.Producto_Id
where f0b.Order_Id=f1.Id
) f3
WHERE f1.FechaPick is not null and (isnull(f2.NbProd, 0) - (isnull(f2.NbProd, 0) - isnull(f3.NbProdLiveRMANull, 0))) >0
ORDER BY $sort $order

Mysql not recognizing Field Names on Stored Procedure

I am trying to create a Stored Procedure where the user can select on the front end how to group the data pulled from mysql. But from some reason when I am trying to execute the query, MySql returns the error:
Query Error (exportEntries): Unknown column 'NumeroProducto' in 'field list'
I got this error by using some error handling code ($mysqli->error).
This is the code I am using to call the stored procedure in PHP:
$client = "CLT_6840";
$planta = $_GET['planta'];
$agrupacion = $_GET['agrupadoPor'];
$qry = "CALL exportEntradas('$cliente','$planta', $agrupacion)";
$stmt = $db->prepare($qry) or die('Prepare error (exportEntries): ' . $db->error);
$stmt->bind_param('sss',
$cliente,
$planta,
$agrupacion
);
$stmt->execute() or die('Execute error (entradas_generales): ' . $db->error);
And this is how my MySql Stored Procedure looks like:
CREATE DEFINER = `prolog`#`%` PROCEDURE `bd_demo_13`.`exportEntradas`( IN cliente VARCHAR(10), IN planta VARCHAR(10), IN C_AGRUPACION VARCHAR(20))
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
SELECT
eb.sCvePlanta AS Planta,
b.iConsecutivo AS IdBultoEntrada,
b.sCveEntradaBodega AS Entrada,
if(b.eTipoSeparacion <> "0", CONCAT(b.sCveEntradaBodega,"-", b.iConsecutivo), b.sCveEntradaBodega) AS NumeroEntrada,
DATE_FORMAT(eb.dFechaLlegadaMercancia, "%Y-%m-%d") AS FechaIngreso,
eb.sNumTalon AS NumeroGuia,
b.iConsecutivo AS idBulto,
b.iCantidadBultos AS CantidadBultos,
IF(eb.iCantidadBultosRecibidos = 1, ctb.sDescripcionSingular, ctb.sDescripcion) AS TipoBultos,
b.eTipoSeparacion AS TipoBulto,
cp.sNombreProveedor AS Proveedor,
eb.sComentariosGenerales AS Comentarios,
f.iFolio AS IdFactura,
f.sNumero AS NumeroFactura,
f.sNumeroPedido AS NumeroOrden,
pf.sCveClienteProveedorProducto AS NumeroProducto,
pf.iCantidadProducto AS CantidadProducto,
umc.sAbrUnidadMedida AS UMC,
cpp.sDescripcionProductoEspanol AS Descripcion,
"Entrada sin referencia" AS FechaCruce,
"Sin Caja" AS Caja,
b.sCveTrafico AS Referencia,
IF(b.sCveTrafico IS NOT NULL, CONCAT("En trámite. ", IF(mce.Comentario IS NULL, "", mce.Comentario)), mce.Comentario) AS ComentariosPropios,
#CASE WHEN b.sCveTrafico IS NOT NULL
# THEN CONCAT("Listo para cruzar. ",mce.Comentario)
# #THEN "Listo para cruzar"
# ELSE mce.Comentario
#END AS ComentariosPropios,
mce.SOT AS SOT,
mce.motivoSOT AS MotivoSOT,
mce.tiempoExtraFechaInicio AS teFechaInicio,
mce.tiempoExtraHoraInicio AS teHoraInicio,
mce.tiempoExtraFechaFin AS teFechaFin,
mce.tiempoExtraHoraFin AS teHoraFin,
mce.tiempoExtraMotivo AS teMotivo,
mce.tiempoExtraDiaFestivo AS teDiaFestivo,
mce.tiempoExtraImporte AS teImporte,
mr.pkIdRetrabajo AS Retrabajos
FROM cb_bulto b
LEFT JOIN cb_entrada_bodega eb ON b.sCveEntradaBodega = eb.sCveEntradaBodega
LEFT JOIN ct_bulto ctb ON eb.sCveBulto = ctb.sCveBulto
LEFT JOIN cu_cliente_proveedor cp ON eb.sCveProveedor = cp.sCveProveedor AND eb.sCveCliente = cp.sCveCliente
LEFT JOIN cb_relacion_remesa_banco_facturas rrbf ON b.iConsecutivo = rrbf.iConsecutivoBulto
LEFT JOIN cb_factura f ON rrbf.iFolio = f.iFolio
LEFT JOIN cb_producto_factura pf ON f.iFolio = pf.iFolio AND f.sCveCliente = pf.sCveCliente AND f.sCveProveedor = pf.sCveProveedor
LEFT JOIN ct_unidad_medida_comercializacion umc ON pf.sCveUMC = umc.sCveUMC
LEFT JOIN cu_cliente_proveedor_producto cpp ON pf.sCveClienteProveedorProducto = cpp.sCveClienteProveedorProducto AND pf.sCveCliente = cpp.sCveCliente AND pf.sCveProveedor = cpp.sCveProveedor
LEFT JOIN mahle.comentariosentradas mce ON eb.sCveEntradaBodega = mce.fkIdEntrada AND b.iConsecutivo = mce.fkIdBulto
LEFT JOIN cb_trafico t ON b.sCveTrafico = t.sCveTrafico
LEFT JOIN cb_detalle_orden_carga doc ON t.sCveTrafico = doc.sCveTrafico AND b.iConsecutivo = doc.iConsecutivoBulto
LEFT JOIN cb_orden_carga oc ON doc.iConsecutivoOrdenCarga = oc.iConsecutivo
LEFT JOIN cb_remesa_consolidada_factura rcf ON f.iFolio = rcf.iFolioFactura
LEFT JOIN mahle.retrabajos mr ON mr.fkIdEntrada = eb.sCveEntradaBodega AND mr.fkIdBulto = b.iConsecutivo
WHERE eb.sCveCliente = cliente
AND (b.sCveTrafico IS NULL OR (b.sCveTrafico IS NOT NULL AND oc.iConsecutivo IS NULL))
AND eb.dFechaLlegadaMercancia <= NOW()
AND eb.dFechaLlegadaMercancia >= "2017-01-01"
AND (
(eb.sCvePlanta = planta AND eb.sCveCliente = "CLT_6840") OR
((eb.sCvePlanta IS NULL OR eb.sCvePlanta IS NOT NULL) AND eb.sCveCliente <> "CLT_6840")
)
GROUP BY C_AGRUPACION;
END
The value contained in $_GET['agrupadoPor'] is NumeroProducto and I have also tried using the actual value of the field: pf.sCveClienteProveedorProducto
As you can see the field name actually do exist. Any idea why this may be happening .. and furthermore .. how I can correct it?

php calling mysql procedure doesn't retrieve a result

I'm here again to ask help again, I'm already created a store procedure in mysql, when a call it on a sgb like SQLyog or MySQL Workbench, I retrieve a result of my query normally, but when I do the same thing on the php and execute mysql_query, nothing is given.
This is my function to execute a mysql query.
function conect($SERVER){
if (strtoupper($SERVER) =='MYSQL') {
$this->con=mysql_connect(SQL_SERVER,SQL_USER,SQL_PASSWD)or die(mysql_error());
$this->db=mysql_select_db(SQL_DB,$this->con);
if ($this->con == 0){
$retorno = "CONECTION ERROR - SERVER!<br>";
}
else if ($this->db == 0){
$retorno = "CONECTION ERROR - DATA BASE!<br>";
} else {
$retorno = "";
}
return $retorno;
}
}
function isConected(){
if($this->con == false)
return false;
return true;
}
function execute($qry, $res="load"){
if(!$this->isConected())
$this->conect('MYSQL');
$this->result[$res] = mysql_query($qry, $this->con) or trigger_error(mysql_error() . ": \n" . __FILE__ . ": \n" . $res . " - " . $qry);
if($this->result[$res])return true;
trigger_error(mysql_error());
return false;
}
function get_fetch_assoc($res="load"){
return mysql_fetch_assoc($this->result[$res]);
}
And this is my procedure call
$mysql = new conexao();
$qry = "CALL spGetChamadoMaisAntigo('".$uareas."', '".$_SESSION["dpto_codigoUrl"]."')";
$mysql->execute($qry, 'Load');
while($row = $mysql->get_fetch_assoc('Load')){
$chamadosAbilitados[] = $row;
}
I have tested this function doing a simple query using a
select * from tableName
and it returned a result normally.
Here is my procedure
DELIMITER $$
DROP PROCEDURE IF EXISTS `ocomon_rc6`.`spGetChamadoMaisAntigo`$$
CREATE DEFINER=`renancr`#`%` PROCEDURE `spGetChamadoMaisAntigo`(IN Sistema VARCHAR(1000),IN CodigoUrl INT)
BEGIN
CALL lib_Explode( ',' , Sistema );
DROP TABLE IF EXISTS ocomon_rc6.TempChamados;
CREATE TABLE IF NOT EXISTS ocomon_rc6.TempChamados(numero INT, dias_apos_abertura INT);
INSERT INTO TempChamados(numero, dias_apos_abertura)
SELECT
o.numero,
(CASE
WHEN CONVERT(NOW(), TIME) > CONVERT(o.data_abertura, TIME) THEN DATEDIFF(NOW(), o.data_abertura)
ELSE DATEDIFF(DATE_SUB(NOW(),INTERVAL 1 DAY), o.data_abertura)
END)
FROM
ocorrencias as o
LEFT JOIN
sistemas AS a ON
a.sis_id = o.sistema
LEFT JOIN
sistemas_x_url AS su ON
a.sis_id = su.sis_id
LEFT JOIN
urls ON
su.codigoUrl = urls.codigoUrl
LEFT JOIN
localizacao AS l ON
l.loc_id = o.local
LEFT JOIN
instituicao AS i ON
i.inst_cod = o.instituicao
LEFT JOIN
usuarios AS u ON
u.user_id = o.operador
LEFT JOIN
usuarios AS ua ON
ua.user_id = o.aberto_por
LEFT JOIN
`status` AS s ON
s.stat_id = o.status
LEFT JOIN
status_categ AS stc ON
stc.stc_cod = s.stat_cat
LEFT JOIN
problemas AS p ON
p.prob_id = o.problema
LEFT JOIN
sla_solucao AS sls ON
sls.slas_cod = p.prob_sla
LEFT JOIN
prioridades AS pr ON
pr.prior_cod = l.loc_prior
LEFT JOIN
sla_solucao AS slr ON
slr.slas_cod = pr.prior_sla
LEFT JOIN
script_solution AS sol ON
sol.script_cod = o.oco_script_sol
LEFT JOIN
prior_atend AS prioridade_atendimento ON
prioridade_atendimento.pr_cod = o.oco_prior
LEFT JOIN
sistemas_x_filtro AS filtr ON
filtr.codigoSistemaFiltro = o.filtro
WHERE
s.stat_painel IN (2)
AND o.sistema IN (SELECT val FROM lib_Explode)
AND su.codigoUrl = CodigoUrl
AND o.oco_scheduled = 0
ORDER BY
o.data_abertura;
DROP TABLE IF EXISTS lib_Explode;
SELECT * FROM TempChamados WHERE dias_apos_abertura = (SELECT MAX(dias_apos_abertura) FROM TempChamados);
DROP TABLE IF EXISTS ocomon_rc6.TempChamados;
END$$
DELIMITER ;
Someone have an idea what I'm doing so wrong?
Solved, I have analyzed this tutorial http://www.joeyrivera.com/2009/using-mysql-stored-procedures-with-php-mysqlmysqlipdo/ and it gives me a answer, need to declare all param it need send out to the php, and insert into this parameters the result of select, I have modifyed my procedure, and called the procedure with this output parameters with # and finaly did a simple select of this output parameters with #, like below.
Altered the parameters of the procedure
DROP PROCEDURE IF EXISTS `ocomon_rc6`.`spGetChamadoMaisAntigo`$$
CREATE DEFINER=`renancr`#`%` PROCEDURE `spGetChamadoMaisAntigo`(IN Sistema VARCHAR(1000),IN CodigoUrl INT, OUT numero INT, OUT diasAposAbertura INT)
Altered the internar select and insert it into the out parameters
SELECT idOcorrencia, dias_apos_abertura INTO numero , diasAposAbertura FROM TempChamados WHERE dias_apos_abertura = (SELECT MAX(dias_apos_abertura) FROM TempChamados);
In the php I changed the call of procedure like below.
$qry = "CALL spGetChamadoMaisAntigo('".$uareas."', '".$_SESSION["dpto_codigoUrl"]."', #numero , #diasAposAbertura)";
$mysql->execute($qry, 'Load');
And finally I did a select of this output parameters like below.
$qry = "SELECT #numero , #diasAposAbertura";
$mysql->execute($qry, 'Load');

MultyQuery is working in phpmyadmin, is not working in Mysqli, did work on an other server

I'm using Msqli to make a multiquery, the query works exactly like i want within phpmyadmin.
it do not work with mysqli anymore. The query did not change between servers.
The query below Was working in a previous LAMP installation but not in the current.
$SQLquery ='set #type = \'\';
set #num = 1;
SELECT
RA.`DATE` as DATES,
RA.`ADDR` as ADDR,
RA.`QID` as QID,
RT.`TAGS` as TAG,
Q.`id` AS QUID,
Q.`ADDR` AS QADDR,
Q.`ORIGINALTEXT` AS QTEXTS,
Q.`DATE` AS QDATES,
cs.`id` AS CUID,
cs.`ADDR` AS CADDR,
cs.`ORIGINALTEXT` AS CTEXTS,
cs.`DATE` AS CDATES,
sol.`id` AS SUID,
sol.`ORIGINALTEXT` AS STEXTS,
sol.`ADDR` AS SADDR,
sol.`DATE` AS SDATES,
prj.`id` AS PUID,
prj.`ORIGINALTEXT` AS PTEXTS,
prj.`ADDR` AS PADDR,
prj.`DATE` AS PDATES,
Max(Q.`DATE` ) AS Q,
Max(cs.`DATE` ) AS C,
Max(sol.`DATE` ) AS S,
Max(prj.`DATE` ) AS P,
##num as row_number
#num:= if(#type = RA.`ADDR`, 1+#num, 1) as v_number,
#type := RA.`ADDR` as dummy
FROM (SELECT `id`,`TAGS`, `QID` from `REL_TAG` ) AS RT
inner Join (SELECT `DATE`, `ADDR`, `QID` from `REL_ADDR` order by DATE) AS RA ON ( RT.`QID` = RA.`QID`)
Left outer Join (SELECT `id`,`DATE`, `ADDR`, `QID`, `ORIGINALTEXT` FROM `QUESTION`) AS Q ON ( RT.`QID` = Q.`QID`) and Q.`ADDR` = RA.`ADDR`
Left outer Join (SELECT `id`,`DATE`, `ADDR`, `QID`, `ORIGINALTEXT` FROM `CASES` order by `CASES`.`DATE`) AS cs ON ( RT.`QID` = cs.`QID`) and cs.`ADDR` = RA.`ADDR`
Left outer Join (SELECT `id`,`DATE`, `ADDR`, `QID`, `ORIGINALTEXT` FROM `SOLUTION` order by `SOLUTION`.`DATE`) AS sol ON ( RT.`QID` = sol.`QID`) and sol.`ADDR` = RA.`ADDR`
Left outer Join (SELECT `id`,`DATE`, `ADDR`, `QID`, `ORIGINALTEXT` FROM `PROJECT` order by `PROJECT`.`DATE`) AS prj ON ( RT.`QID` = prj.`QID`) and prj.`ADDR` = RA.`ADDR`
where RT.`QID` = \''.NbOnly($Fetchmodifier).'\' Group by `QID`, addr, v_number LIMIT '.$Anstart.' ,'.$Ansnb.';';
Update
The query does not return any error in the logs, it just return nothing (null).
Here is the PHP code to execute the MySQLi Multiquery
$mysqlin = new mysqli("localhost", "user", "pass", "db");
if (mysqli_error($mysqlin)) {
outputdataXML(sprintf("Connect Problem : %s\n", mysqli_error($mysqlin)));
exit();
}
if ($mysqlin->multi_query($SQLquery)) {
do {
if ($result = $mysqlin->store_result()) {
while ($row = $result->fetch_array(MYSQLI_BOTH)) {
if( $Foundrows = $row[0]){ //Maybe the problem is here ?
$Outputvalue[] = FormatFile($row);
}
}
$result->free();
}
if ($mysqlin->more_results()) {
}
} while ($mysqlin->more_results() && $mysqlin->next_result());
}
$mysqlin->close();
I have Found the problem, Some but not all of the tables Were EMPTY,
As in Without any records,
I added a dummy record To each tables, some tables had records but some were without,
and now even if the Query dont matchThe joins are Now still being Made properly.
I Hope this help lots of ppl.
When your using MySQL "Join", you need 1 record in each and All of your joined tables, no matter if it will ever be used ex: 0, 00-00-0000, Null , 0, empty
Only then, all the joinning Tables included in the query will work.

Categories