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');
Related
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?
I'm running a connection with PDO to a local MSSQL database. Running any Stored procedure at all through the connection doesn't give me any error at all.
This one single Stored procedure is giving me the following error:
Error in SQL: [Microsoft][SQL Server Native Client 10.0]Invalid cursor state - Query: exec sp_Get_SaldosWeb #Tipo=1, #IdDato=15368
This is my current PDO string for connecting inside this function and returning the array:
$query = $this->db->prepare($qry, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$final = $query->execute();
$this->setRows($query);
if(!$final) {
$this->error($qry, $query, $ret);
} else {
return $query->fetchAll();
}
I've tried closing the cursor both before the execute and after fetchAll like so:
$rows = $query->fetchAll();
$query->closeCursor();
return $rows;
But that also doesn't work. FYI, there are no queries executed before this call to this stored procedure anywhere in my code.
Not sure why this stored procedure is giving so many errors. If I run this exact same SP from MSSQL Management console it runs fine and returns 3 rows.
EDIT:
Here is the stored procedure:
USE [DBNAME]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[sp_Get_SaldosWeb]
#Tipo int , --1 = Alumno 2 = Familia
#IdDato int
as
if #Tipo = 1
begin
select SC_Alumno.Codigo ,
SC_Alumno.Nombres + ' ' + SC_Alumno.Apellidos as [Nombre],
SC_Moneda.Nombre as Moneda, upper(replace(replace(replace(replace(replace( replace(lower(SC_TipoCargo.Nombre),char(237),'i'), char(243),'o'), char(233),'e') , char(225),'a') ,char(250),'u'),char(241),'ñ')) as [Tipo de Cargo]
, cast(round(Sum(SC_CargoxAlumno.Debe),2) as decimal(18,2)) as Monto ,
SC_Alumno.Codigo as Codigo2
from SC_CargoxAlumno
inner join SC_Moneda on SC_CargoxAlumno.IdSC_Moneda = SC_Moneda.IdSC_Moneda
inner join SC_TipoCargo on SC_CargoxAlumno.IdSC_TipoCargo = SC_TipoCargo.IdSC_TipoCargo
inner join SC_Alumno on SC_Alumno.IdSC_Alumno = SC_CargoxAlumno.IdSC_Alumno
inner join SC_Familia on SC_Alumno.IdSC_Familia = SC_Familia.IdSC_Familia
where
SC_Alumno.IdSC_Alumno = #IdDato
and SC_CargoxAlumno.Debe <> 0
group by
SC_Alumno.Codigo ,
SC_Alumno.Nombres + ' ' + SC_Alumno.Apellidos ,
SC_Moneda.Nombre , SC_TipoCargo.Nombre
end
else
begin
select SC_Alumno.Codigo ,
SC_Alumno.Nombres + ' ' + SC_Alumno.Apellidos as [Nombre],
SC_Moneda.Nombre as Moneda, upper(replace(replace(replace(replace(replace( replace(lower(SC_TipoCargo.Nombre),char(237),'i'), char(243),'o'), char(233),'e') , char(225),'a') ,char(250),'u'),char(241),'ñ')) as [Tipo de Cargo] ,
cast(round(Sum(SC_CargoxAlumno.Debe),2) as decimal(18,2)) as Monto ,
SC_Alumno.Codigo as Codigo2
from SC_CargoxAlumno
inner join SC_Moneda on SC_CargoxAlumno.IdSC_Moneda = SC_Moneda.IdSC_Moneda
inner join SC_TipoCargo on SC_CargoxAlumno.IdSC_TipoCargo = SC_TipoCargo.IdSC_TipoCargo
inner join SC_Alumno on SC_Alumno.IdSC_Alumno = SC_CargoxAlumno.IdSC_Alumno
inner join SC_Familia on SC_Alumno.IdSC_Familia = SC_Familia.IdSC_Familia
where
SC_Familia.IdSC_Familia = #IdDato
and SC_CargoxAlumno.Debe <> 0
group by
SC_Alumno.Codigo ,
SC_Alumno.Nombres + ' ' + SC_Alumno.Apellidos ,
SC_Moneda.Nombre , SC_TipoCargo.Nombre
end
Add "SET NOCOUNT ON" to the beginning of your procedure.
You might find references here :
PHP Data Objects
My stored procedure "best practices" checklist
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}'";
}
function sum($nomId){
$sql = "SELECT SUM(nomDetCantidad) FROM table2 where Id = $nomId";
$Resultado=$this->ProcesaSQLQueryList($sql);
if($Resultado>0){
foreach($Resultado as $key => $valor){
$cantidadTotal = $valor[0];
}
}
if($Resultado=='null'){$cantidadTotal=0;}
$sql = "UPDATE table1 SET nomCantidadTotal=$cantidadTotal,nomActualizado = NOW() WHERE nomId= $nomId";
return $this->ProcesaSQLQueryUpdate($sql);
and this is the function I call
function ProcesaSQLQueryList($SQLQuery){
$row= array();
if(!$this->link_mysql) $this->link_mysql = conectarManager();
if($res = mysql_query($SQLQuery,$this->link_mysql)){
while($r = mysql_fetch_array($res)){
$row[] = $r;
}
mysql_free_result($res);
return $row;
}else{
$this->last_error = $SQLQuery . " - " . mysql_error();
return -1;
}
}
So I sum up whatever I have in a field table 2 with the foreign key of table 1 then my result gets updated to the table 1 field but if I delete the fields in table 2 result wont get updated to 0 any suggestions I'm pretty sure this is an easy one but can't seem to find it
$sql = "SELECT SUM(nomDetCantidad) FROM table2 where nominaId = $nomId";
$Resultado = $this->ProcesaSQLQueryList($sql);
if ($Resultado > 0) {
foreach ($Resultado as $key => $valor) {
$cantidadTotal = $valor[0];
}
}
if ($cantidadTotal == '') {
$cantidadTotal=0.00;
}
$sql = "UPDATE table1 SET nomCantidadTotal=$cantidadTotal,nomActualizado = NOW() WHERE nomId = $nomId";
return $this->ProcesaSQLQueryUpdate($sql);
There! It was sending me a blank variable xD but fixed and there are more suitable ways to do it, I agree with Spencer but if a client wants a red swing he has to get a red swing you know? :) thanks for the help guys!
If you need a zero returned when there are no "matching" rows in table2, then wrap the return expression in an IFNULL function.
SELECT IFNULL(SUM(nomDetCantidad),0) FROM table2 ...
You could significantly reduce the amount of code you have, reduce the number of roundtrips to the database, and improve performance by doing all this work in a single UPDATE statement. You can use either a correlated subquery or an OUTER JOIN:
-- using a correleated subquery
UPDATE table t1
SET t1.nomActualizado = NOW()
, t1.nomCantidadTotal =
( SELECT IFNULL(SUM(t2.nomDetCantidad),0) AS nomCantidadTotal
FROM table2 t2
WHERE t2.Id = t1.nomID
)
WHERE t1.nomId = $nomId
-- using an OUTER JOIN
UPDATE table1 t1
LEFT
JOIN (SELECT t2.Id, SUM(t2.nomDetCantidad) AS nomCantidadTotal
FROM table2 t2
WHERE t2.Id = $nomId
GROUP BY t2.Id
) s
ON s.Id = t1.nomID
SET t1.nomCantidadTotal = IFNULL(s.nomCantidadTotal,0)
, t1.nomActualizado = NOW()
WHERE t1.nomID = $nomId
It's not at all clear why you need to store this total on table1, when you could derive it from table2 whenever you need it, without storing that value on table1 at all...
SELECT t1.nomId
, IFNULL((SELECT SUM(t2.nomDetCantidad) AS nomCantidadTotal
FROM table2 t2
WHERE t2.Id = t1.nomID
),0) AS nomCantidadTotal
FROM table1 t1
WHERE t1.nomId = $nomId
The following MySQL query runs in PHP without errors, but the resultset is empty. Directly outputting the query string to a file and running the query in the MySQL client using 'source [filename]' returns several rows of results, as expected.
Is there something that would cause this query not to work with PHP? categorylinks.cl_to and smw_spec2.value_string are both varbinary(255). Show create table indicates engine=InnoDB and default charset=binary.
Things I have tried without success:
$sql = preg_replace("/[\n\t]+/", " ", $sql);
Changing '_wpg' and 'Derp' to CAST('_wpg' AS BINARY(255))
Changing '_wpg' and 'Derp' to BINARY '_wpg'
I am using the MediaWiki DatabaseMysql class to execute the query and fetch rows, but it's a very thin abstraction, and I'm certain it's not the problem (see below).
SELECT
prop.name AS prop_name, prop.count AS prop_count, prop.type AS prop_type,
val.value AS val_value, val.unit AS val_unit, val.count AS val_count
FROM
(
SELECT
s_id, name, type, COUNT(foo.name) AS count
FROM (
(
SELECT
cl.cl_to AS cat_name, s.smw_id AS s_id, s.smw_sortkey AS name, spec.value_string AS type
FROM `smw_ids` s
INNER JOIN (`categorylinks` cl, `page` p, `smw_ids` s2, `smw_atts2` a)
ON (cl.cl_from = p.page_id AND
p.page_title = s2.smw_title AND
s2.smw_id = a.s_id AND
a.p_id = s.smw_id)
LEFT JOIN `smw_spec2` spec ON s.smw_id = spec.s_id
)
UNION ALL
(
SELECT
cl.cl_to AS cat_name, s.smw_id AS s_id, s.smw_sortkey AS name, '_wpg' AS type
FROM `smw_ids` s
INNER JOIN (`categorylinks` cl, `page` p, `smw_ids` s2, `smw_rels2` a)
ON (cl.cl_from = p.page_id AND
p.page_title = s2.smw_title AND
s2.smw_id = a.s_id AND
a.p_id = s.smw_id)
)
) AS foo
WHERE foo.cat_name = 'Derp'
GROUP BY name
ORDER BY count DESC
LIMIT 10
) AS prop
INNER JOIN
(
SELECT
bar.p_id AS p_id, bar.value AS value, bar.unit AS unit, COUNT(bar.value) AS count,
IF( #prev != p_id, #rownum := 1, #rownum := #rownum+1 ) AS rank,
#prev := p_id
FROM (
(SELECT a.p_id AS p_id, a.value_xsd AS value, a.value_unit AS unit FROM `smw_atts2` a)
UNION ALL
(SELECT r.p_id AS p_id, s.smw_sortkey AS value, NULL AS unit
FROM `smw_rels2` r INNER JOIN `smw_ids` s ON r.o_id = s.smw_id)
) AS bar
GROUP BY value, unit
ORDER BY count DESC
) AS val
ON prop.s_id = val.p_id
WHERE val.rank <= 50
ORDER BY prop_count DESC, prop_name, val_count DESC, val_value
Edit: The following test script outputs nothing. query.sql contains exactly the query above, written to file immediately preceding the mysql_query() call in MediaWiki's database class.
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('mediawiki', $db);
$res = mysql_query(file_get_contents("query.sql"), $db);
while ($row = mysql_fetch_assoc($res)) {
var_dump($row);
}
echo mysql_error($db);
Edit: I imported a huge database dump and afterwards, when I loaded the PHP page, there was a noticeable wait that seemed to indicate that the query was running, but still no results showed. I ended up reworking the query, and I no longer have this problem.
Try this to detect and report errors better:
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('mediawiki', $db);
$res = mysql_query(file_get_contents("query.sql"), $db);
if (!$res) {
print "SQL Error ".mysql_errno().":".mysql_error().", from query: '".file_get_contents("query.sql")."'";
} else {
while ($row = mysql_fetch_assoc($res)) {
var_dump($row);
}
}
Try this after mysql_connect:
mysql_query('SET NAMES utf8;');