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?
Related
I have the following PHP code that works perfectly ($qry_str is actually generated in the PHP):
$qry_str = <<<'QRY'
FIND_IN_SET('6-47', attributes)
AND FIND_IN_SET('4-176', attributes)
AND FIND_IN_SET('9-218', attributes)
QRY;
$pdo->query('DROP TEMPORARY TABLE IF EXISTS `temp_attr`');
$temp_sql = <<<"TEMP"
CREATE TEMPORARY TABLE IF NOT EXISTS `temp_attr` (
SELECT product_id, GROUP_CONCAT(CONCAT(group_id, '-', IF (custom_value != '', custom_value, value_id)) SEPARATOR ',') AS attributes
FROM `products_attributes`
GROUP BY `product_id`
HAVING $qry_str
);
TEMP;
$pdo->query($temp_sql);
$sql = "SELECT
m.recommended_price AS msrp,
m.purchase_price AS cost,
pp.USD AS regular_price,
pc.USD AS special_price,
pc.start_date AS start_date,
pc.end_date AS end_date,
pl.permalink AS permalink,
pi.name AS description,
m.sku AS sku,
m.default_category_id AS cat,
m.id AS prod_id
FROM `products` AS m
LEFT JOIN `products_prices` AS pp ON m.id = pp.product_id
LEFT JOIN `products_campaigns` AS pc ON m.id = pc.product_id
LEFT JOIN `permalinks` AS pl ON (m.id = pl.resource_id AND pl.resource = 'product')
LEFT JOIN `products_info` AS pi ON (m.id = pi.product_id)
LEFT JOIN `products_to_categories` AS ptc ON (m.id = ptc.product_id)
INNER JOIN `temp_attr` AS pa
WHERE ptc.category_id = :cat
AND m.status = 1
AND m.id = pa.product_id
LIMIT 55;
";
$data = $pdo->prepare($sql)
->bindValue('cat', 100)
->execute()
->fetchAll();
However, when I use a placeholder in the temp table code, i.e.
$temp_sql = <<<"TEMP"
CREATE TEMPORARY TABLE IF NOT EXISTS `temp_attr` (
SELECT product_id, GROUP_CONCAT(CONCAT(group_id, '-', IF (custom_value != '', custom_value, value_id)) SEPARATOR ',') AS attributes
FROM `products_attributes`
GROUP BY `product_id`
HAVING :qry_str
);
TEMP;
$sth = $pdo->prepare($temp_sql);
$sth->bindValue('qry_str', $qry_str, PDO::PARAM_STR);
$sth->execute();
I get the following error:
PHP Fatal error: Uncaught PDOException: SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect DOUBLE value: 'FIND_IN_SET('6-47', attributes)
AND FIND_IN_SET('4-176', attributes)
AND FIND_IN_SET('9-218', attributes)
AND FIND_IN_SET(...'
There are no datetime columns in this table.
group_id and value_id are integer columns
Since the code works fine without the placeholder, I'm at a loss as to why the use of a placeholder breaks the code. The placeholder in the main SQL works properly.
PHP 8.0
https://dev.mysql.com/doc/refman/8.0/en/prepare.html explains:
Parameter markers can be used only where data values should appear, not for SQL keywords, identifiers, and so forth.
In your case, you're apparently trying to bind an expression with the FIND_IN_SET() function. You can't do that. All expressions and other SQL syntax must be fixed in the query at the time you prepare it. You can use a parameter only in a place where you would otherwise use a scalar literal value. That is, a quoted string or a numeric literal.
I have an internal intranet made in PHP and we had the Oracle server here, but it has been moved to an cloud server. Since that I'm having an issue.
If I execute a simple query from PHP like "select * from empresas" it executes normal, but if I try a more complicated query, with some joins and where clause, it gives the error ORA-03113. Trying to execute from PL/SQL Developer, this specific query takes something like 5 seconds to execute, it returns something like 15 rows only.
I have no acces to the Oracle logs, because this cloud is just one instance to us.
I think that maybe is a PDO configuration or maybe version that I need to configure/check to solve this problem, just don't know how to start.
The old Oracle server was a Windows server and the Oracle version was 12. The cloud is Oracle 11 and is a Linux server.
Here is the query:
`SELECT distinct
ct.descricao MARCA,
e.nome EMPRESA,
vi.cod_item CODIGO,
i.descricao DESCRICAO,
igi.cod_grupo_interno CODTIPO,
igi.descricao TIPO,
ic.cod_curva CLASSEABC,
v.cod_cliente COD_CLIENTE,
cd.nome NOME_CLIENTE,
ci.descricao CID_CLIENTE,
ci.uf UF_CLIENTE,
CASE WHEN cd.cpf<>' ' THEN 'F' ELSE 'J' END TIPO_CLIENTE,
cl.descricao DESCTP_CLIENTE,
SUM(vi.qtde) QTDE,
vi.preco_unitario PPUBLICO,
SUM(vi.qtde * vi.preco_unitario) FAT_BRT,
SUM(vi.TOTAL_DESCONTOS) DESCONTO,
SUM(vi.preco_liquido_final) FAT_LIQ,
SUM(vi.qtde * vi.preco_contabil) CUSTO,
SUM(vi.base_icms) BASE_ICMS,
SUM(vi.valor_icms) VLR_ICMS,
'0' VLR_COP,
'0' ACRESCIMO,
SUM(vi.valor_pis + vi.valor_cofins) VLR_PCOF,
SUM(vi.valor_ipi) VLR_IPI,
NULL VLR_MARGEM,
v.controle|| '-' || v.serie NF,
TO_CHAR(v.emissao, 'DD/MM/YYYY') DTNF,
n.cod_natureza CODNATUREZA,
n.descricao NATUREZA,
eu.id_funcionario VENDEDOR,
eu.nome_completo FUNCIONARIO,
eu.nome LOGIN,
eu.cod_funcao TIPO_FUN,
'N' STATUS,
v.numero_os OS,
v.chassi_resumido VEICULO,
cd.bairro BAIRRO_CLIENTE,
v.controle|| '-' || v.serie NOTA,
pg.descricao CONDICAO_PG,
pg.cod_forma_pgto COD_CONDICAO,
os.tipo CD_TP_OS,
ost.descricao DS_TP_OS,
'0' PERCUSTOOPER,
ed.cod_empresa_departamento DEPARTAMENTO,
ic.custo_fornecedor VLRREPOSICAO
FROM vendas v
INNER JOIN venda_itens vi ON vi.cod_empresa = v.cod_empresa and vi.controle = v.controle
INNER JOIN itens_custos ic ON ic.cod_empresa = v.cod_empresa AND ic.cod_item = vi.cod_item AND ic.cod_fornecedor = vi.cod_fornecedor
INNER JOIN itens_fornecedor if ON if.cod_item = vi.cod_item AND if.cod_fornecedor = vi.cod_fornecedor
INNER JOIN fornecedor_estoque fe ON fe.cod_fornecedor = if.cod_fornecedor
INNER JOIN itens i ON i.cod_item = vi.cod_item
INNER JOIN itens_grupo_interno igi ON igi.cod_grupo_interno = i.cod_grupo_interno
INNER JOIN empresas e ON e.cod_empresa = v.cod_empresa
INNER JOIN empresas_usuarios eu ON eu.nome = v.vendedor
INNER JOIN empresas_funcoes ef ON ef.cod_funcao = eu.cod_funcao
INNER JOIN empresas_departamentos ed ON ed.cod_empresa = v.cod_empresa AND ed.cod_empresa_departamento = v.cod_empresa_departamento
INNER JOIN parm_sys p ON p.cod_empresa = v.cod_empresa
INNER JOIN concessionaria_tipo ct ON ct.cod_tipo_concessionaria = p.tipo_concessionaria
INNER JOIN cliente_diverso cd ON cd.cod_cliente = v.cod_cliente AND cd.cod_empresa = v.cod_empresa
INNER JOIN clientes_tipo cl ON cl.cod_tipo = cd.cod_tipo
INNER JOIN cidades ci ON ci.cod_cidades = cd.cod_cidades
LEFT JOIN pagamento_venda pv ON pv.controle = v.controle AND pv.serie = v.serie
LEFT JOIN forma_pgto pg ON pg.cod_forma_pgto = pv.cod_forma_pgto
LEFT JOIN os ON os.cod_empresa = v.cod_empresa and os.numero_os = v.numero_os
LEFT JOIN os_tipos ost ON ost.tipo = os.tipo
LEFT JOIN natureza n ON n.cod_natureza = vi.cod_natureza and n.grupo = vi.grupo
LEFT JOIN operacoes ops ON ops.cod_empresa = v.cod_empresa and ops.cod_operacao = v.cod_operacao
WHERE v.status <> '1' AND v.total_produtos > 0
AND (ops.grupo is null or ops.grupo = 2)
AND v.emissao >= to_date(SYSDATE-20)
AND i.COD_GRUPO_INTERNO <> 13
GROUP BY ct.descricao, e.nome, vi.cod_item, i.descricao, igi.cod_grupo_interno, igi.descricao, ic.cod_curva, v.cod_cliente,
cd.nome, ci.descricao, ci.uf, CASE WHEN cd.cpf<>' ' THEN 'F' ELSE 'J' END, cl.descricao, vi.preco_unitario, vi.preco_contabil,
v.margem, v.controle|| '-' || v.serie, TO_CHAR(v.emissao, 'DD/MM/YYYY'), n.cod_natureza, n.descricao, eu.id_funcionario,
eu.nome_completo, eu.nome, eu.cod_funcao, v.numero_os, v.chassi_resumido, cd.bairro, v.controle|| '-' || v.serie,
pg.descricao,pg.cod_forma_pgto, os.tipo, ost.descricao, ed.cod_empresa_departamento, ic.custo_fornecedor`
I asked the administers for Oracle logs, it gave me nothing, the administers saw that my query even got to there, then I tried a lot of things and finally my boss found an answer. He saw that the problem is the size of the package the PHP are sending through the VPN connection we have with the cloud. So the solution (at least for now) is add to PDO connection the size we need using: "(DESCRIPTION=(SDU=1400) ..." on the connection string.
For all those that care, I found that I needed to re read the basics on querying. Once sorted, I realised I had a fair few errors throughout my code.
I've got a query I'm trying to build and I'm throwing up error after error regarding to ambiguity. Would anyone kindly show me how to execute MySQL aliases properly?
This is my code so far. It worked fine until I put the join in there. I suspect it's because I'm referencing 'wine' more than once in the same query, but that may be one of many problems.
$query =
"SELECT
wine_id,
wine_name,
winery_name,
region_name,
year,
variety
FROM
wine AS w,
winery,
region,
grape_variety
JOIN
wine
ON
grape_variety.variety_id = wine.wine_id
JOIN
wine_variety
ON
wine.wine_id = wine_variety.variety_id
WHERE
winery.region_id = region.region_id
AND
wine.winery_id = winery.winery_id";
if (!empty($wineName)) {
$query .= " AND wine_name = '{$wineName}'";
}
if (!empty($wineryName)) {
$query .= " AND winery_name = '{$wineryName}'";
}
// If the user has specified a region, add the regionName
// as an AND clause
if (isset($regionName) && $regionName != "All") {
$query .= " AND region_name = '{$regionName}'";
}
// If the user has specified a variety, add the grapeVariety
// as an AND clause
if (isset($grapeVariety) && $grapeVariety != "Riesling") {
$query .= " AND variety = '{$grapeVariety}'";
}
Try to do it this way:
SELECT w.wine_id, w.wine_name, winery_name, region_name, year, variety
FROM
wine AS w
join winery on w.winery_id = winery.winery_id
join region on winery.region_id = region.region_id,
join grape_variety on grape_variety.variety_id = w.wine_id
Your query must be like:
SELECT
w.wine_id,
w.wine_name,
wy.winery_name,-- I assume this column from table `wy`
r.region_name, -- column from table `region`
w.year,
w.variety
FROM wine w
INNER JOIN winery wy ON (wy.winery_id = w.winery_id )
INNER JOIN region r ON ( r.region_id = wy.region_id )
INNER JOIN grape_variety gv ON (gv.variety_id = w.wine_id)
INNER JOIN wine_variety wv ON (wv.variety_id = w.wine_id)
...
append other WHERE conditions here
Note: if you give table structure then it would be more clear, at first I assume whatever column you retrieve is from main table and
if all tables in query have same column name then use table_alias_name.column_name.
try this
SELECT
w.wine_id,
w.wine_name,
wy.winery_name,
r.region_name,
r.year,
wv.variety
FROM wine w
INNER JOIN winery wy ON (wy.winery_id = w.winery_id )
INNER JOIN region r ON ( r.region_id = wy.region_id )
INNER JOIN grape_variety gv ON (gv.variety_id = w.wine_id)
INNER JOIN wine_variety wv ON (wv.variety_id = w.wine_id)
Use This one
$query =
"SELECT
w.wine_id,
w.wine_name,
winery.winery_name,
region.region_name,
year,
grape_variety.variety
FROM
wine AS w,
winery,
region,
grape_variety
JOIN
wine
ON
grape_variety.variety_id = wine.wine_id
JOIN
wine_variety
ON
wine.wine_id = wine_variety.variety_id
WHERE
winery.region_id = region.region_id
AND
wine.winery_id = winery.winery_id";
if (!empty($wineName)) {
$query .= " AND w.wine_name = '{$wineName}'";
}
if (!empty($wineryName)) {
$query .= " AND winery.winery_name = '{$wineryName}'";
}
// If the user has specified a region, add the regionName
// as an AND clause
if (isset($regionName) && $regionName != "All") {
$query .= " AND region.region_name = '{$regionName}'";
}
// If the user has specified a variety, add the grapeVariety
// as an AND clause
if (isset($grapeVariety) && $grapeVariety != "Riesling") {
$query .= " AND grape_variety.variety = '{$grapeVariety}'";
}
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');
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.