I'm creating a project in FuelPHP, with php + mysql.
I have this database query (I'm not using their built in query builder because its just a pain in the ass for complex queries).
$sql = DB::query('
SELECT game_id, lati, longi,
acos(sin (' . $lat . ')
* sin (radians( lati ))
+ cos (' . $lat . ')
* cos (radians(lati))
* cos (radians(longi) - ' . $lon . '))
*' . $R . ' AS D
FROM (
SELECT game_id, lati, longi
FROM games
WHERE lati > ' . $minLat .
' AND lati <' . $maxLat .
' AND longi > ' . $minLon .
' AND longi < ' . $maxLon .
') AS firstcut
WHERE
acos(sin (' . $lat . ')
* sin (radians( lati ))
+ cos (' . $lat . ')
* cos (radians(lati))
* cos (radians(longi) - ' . $lon . '))
*' . $R . '<' . $rad .
' ORDER BY D');
If I execute this and print_r(result) the number of rows is displayed i.e 2.
However I cant treat, or convert this result into an array, so I cant
foreach($result as $row) { echo $row['id'] . ' + ' . $row['D']}
Or something similar.
If I paste this code and replace the php variables with real values into phpmyadmin, I get the green 'The query was executed successfully' message but no rows are returned (two rows should be returned, there is not even a 'This query returned zero rows' message).
I dont have much experience with this kind of nested/complex sql queries, so any help would be appreciated.
Thanks.
You need to pass DB::SELECT as the second param for DB::query().
You might want to use the as_array method from the database result. Or take a look here: http://fuelphp.com/docs/classes/database/usage.html#results
Related
I have 2 tables in Joomla:
Entitlements:(User_id, entitlement_amount, reference_year)
Charges:(User_id, charge_amount, reference_year)
Both must be linked to the users core table using the User_id as a foreign key.
Entitlements has entries with users not necessarily included in Charges. Charges table has entries not necessarily included in the Entitlements.
I need to link all 3 tables in such a way so that in each row, I will have the User_id(name), the SUM(entitlement_amount) and the SUM(charge_amount).
The results must be grouped by employee, reference_year.
If no SUM is calculated then to display 0.
Here is my code below.
$query->select( $this->getState(
'list.select',
'a.id,' .
'a.employee_id,' .
'ac.employee_id,' .
'a.reference_year,' .
'ac.reference_year,' .
'u.name,' .
'SUM(a.entitlement), ' .
'SUM(ac.charge)'));
$query->from($db->quoteName('#__employee_entitlement').' AS a');
$query->join('LEFT OUTER', $db->quoteName('#__users', 'u') . ' ON (' .
$db->quoteName('a.employee_id') . ' = ' . $db->quoteName('u.id') .')');
$query->join('LEFT', $db->quoteName('#__absence_charge', 'ac') . ' ON ('
. $db->quoteName('ac.employee_id') . ' = ' . $db->quoteName('u.id') .
')');
$query->group($db->quoteName('a.employee_id')) ;
$query->group($db->quoteName('a.reference_year')) ;
Thanks.
Why is this query not working?
$query = ("SELECT * FROM
(SELECT *, (
(((endingLatitude - " . $h . ")(endingLatitude - " . $h . "))
/" . pow($r1, 2) . ")
+
((endingLongitude - " . $k . ")(endingLongitude - " . $k . "))
/" . pow($r2, 2) . "
) AS point2
FROM (SELECT *, ((
(
((startingLatitude - " . $h . ")(startingLatitude - " . $h . "))
/" . pow($r1, 2) . ")
+
((startingLongitude - " . $k . ")(startingLongitude - " . $k . "))
/" . pow($r2, 2) . "))
AS point1
FROM (SELECT * FROM trips WHERE distance >='" . ($distance * .25) . "') as query1)
as query2) as query3 WHERE point1 <= 1 AND point2 <= 1 LIMIT 0 , 10;");
$result = mysqli_query($con, $query);
$h and $k is the ellipses x and y coordinates respectively. I am using a formula found here to calculate whether or not the two points, (startingLat,startingLong) and (endingLat,endingLong) are within an ellipse with vertical height $r1 and horizontal height $r2. I am also limiting the rows that I search to rows that have a distance cell value of greater than $distance * .25.
I think it might have something to do with a parenthesis error or something to do with the way I am sub querying/performing my calculations.
Using
die(mysqli_error($con));
returns an error of You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(endingLatitude - 36.9564753)) /796.842964388) + ((endingLongitud' at line 3
I believe you have to use Mysql multiplication arithmetic operator, *.
https://dev.mysql.com/doc/refman/5.0/en/arithmetic-functions.html#operator_times
Instead of:
(endingLatitude - " . $h . ")(endingLatitude - " . $h . ")
Do this...
(endingLatitude - " . $h . ") * (endingLatitude - " . $h . ")
I make an unique id, which contain of CURRENT_DATE and character like :
SELECT CONCAT(DATE_FORMAT(CURRENT_DATE,'%Y%m%d'),'Q',
LPAD(MAX(RIGHT(idreport,3))+1,3,'0'))
FROM record.report
result :
20140723Q001
I want every day it start from 001. So, if the query above is correct I would get result like 20140724Q001 today. But I get a wrong result 20140724Q002.
How to reset 3 digit behind the id if the day change?
complete syntax :
$sql="SELECT CONCAT(DATE_FORMAT(CURRENT_DATE,'%Y%m%d'),'Q',LPAD(MAX(RIGHT(idreport,3))+1,3,'0'))
FROM record.report";
$res=mysql_query($sql) or _doError(_ERROR30 . ' (<small>' . htmlspecialchars($sql) . '</small>): ' . mysql_error() );
$dat1=mysql_fetch_array($res, MYSQL_NUM);
if($dat1 == 0){
$sql = "SELECT DATE_FORMAT(CURRENT_DATE,'%Y%m%d')";
$res1=mysql_query($sql) or _doError(_ERROR30 . ' (<small>' . htmlspecialchars($sql) . '</small>): ' . mysql_error() );
$dat2=mysql_fetch_array($res1, MYSQL_NUM);
// first number
$RegNum = $dat2[0]."Q001";
} else {
$RegNum = $dat1[0];
}
Although we can have a more optimized solution, this should do your job-
SELECT CONCAT(DATE_FORMAT(CURRENT_DATE,'%Y%m%d'),'Q',
LPAD(MAX(RIGHT(CASE WHEN LEFT(idreport,8)=DATE_FORMAT(CURRENT_DATE,'%Y%m%d') THEN idreport ELSE '000' END,3))+1,3,'0'))
FROM record.report;
Incase any query, please let me know.
How can I adapt the following query to JDatabase?
SELECT
c.RAZONSOCIAL usu_razonSocial
,c.NIT usu_nit
,c.SEDE usu_sede
,c.EMAIL usu_email
,IF(IFNULL(u.block, 1) = 0, 'Activo', 'Inactivo') usu_estado
,COUNT(ct.ctf_id) nroCertificados
FROM
cargacliente c
INNER JOIN
cargas
ON (crg_id = cargas_id)
AND (crg_status = 'Ok')
INNER JOIN
certificados ct
ON (ctf_sede = SEDE)
AND (ctf_nit = NIT)
LEFT JOIN
database_1.bml_users u
ON (id = user_id)
GROUP BY
c.NIT
,c.SEDE
ORDER BY
usu_razonSocial
,usu_nit
,usu_sede;
This is Joomla 2.5.4.
I have read this post but I couldn't do it.
I tried to do it in this way:
<?php
$query
->select($db->quoteName(array('c.RAZONSOCIAL AS usu_razonSocial', 'c.NIT usu_nit', 'c.SEDE usu_sede', 'c.EMAIL usu_email', 'IF(IFNULL(u.block, 1) = 0, \'Activo\', \'Inactivo\') usu_estado', 'COUNT(ct.ctf_id) nroCertificados')))
->from($db->quoteName('database_2.cargacliente', 'c'))
->join('INNER', $db->quoteName('database_2.cargas','a') . ' ON (' . $db->quoteName('a.crg_id') . ' = ' . $db->quoteName('database_2.cargacert.cargas_id') . ') AND (' . $db->quoteName('a.crg_status') . ' = \'Ok\')')
->join('INNER', $db->quoteName('database_2.certificados','b') . ' ON (' . $db->quoteName('b.ctf_sede') . ' = ' . $db->quoteName('database_2.cargacliente.SEDE') . ') AND (' . $db->quoteName('b.ctf_nit') . ' = NIT)')
->join('LEFT', $db->quoteName('joomla_database.bml_users', 'u') . ' ON (' . $db->quoteName('database_2.usuario.usu_id') . ' = ' . $db->quoteName('joomla_database.bml_users.user_id') . ')')
->group(array('c.NIT', 'c.SEDE'))
->order(array('database_2.usuario.usu_razonSocial', 'database_2.usuario.usu_nit', 'database_2.usuario.usu_sede'));
?>
The error shown is the following:
500 - Ha ocurrido un error.
Unknown column 'c.RAZONSOCIAL usu_razonSocial' in 'field list' SQL=SELECT `c`.`RAZONSOCIAL usu_razonSocial`,`c`.`NIT usu_nit`,`c`.`SEDE usu_sede`,`c`.`EMAIL usu_email`,`IF(IFNULL(u`.`block, 1) = 0, 'Activo', 'Inactivo') usu_estado`,`COUNT(ct`.`ctf_id) nroCertificados` FROM `biochemical`.`cargacliente` AS `c` INNER JOIN `biochemical`.`cargas` AS `a` ON (`a`.`crg_id` = `biochemical`.`cargacert`.`cargas_id`) AND (`a`.`crg_status` = 'Ok') INNER JOIN `biochemical`.`certificados` AS `b` ON (`b`.`ctf_sede` = `biochemical`.`cargacliente`.`SEDE`) AND (`b`.`ctf_nit` = NIT) LEFT JOIN `biochemical_bml`.`bml_users` AS `u` ON (`biochemical`.`usuario`.`usu_id` = `biochemical_bml`.`bml_users`.`user_id`) GROUP BY c.NIT,c.SEDE ORDER BY biochemical.usuario.usu_razonSocial,biochemical.usuario.usu_nit,biochemical.usuario.usu_sede
The changes were the following:
Remove the first $db->quoteName() in the SELECT statement.
Modify ALIAS from tables.
LEFT JOIN modification.
The final code is the following:
$query
->select(array('c.RAZONSOCIAL AS usu_razonSocial', 'c.NIT AS usu_nit', 'c.SEDE AS usu_sede', 'c.EMAIL AS usu_email', 'IF(IFNULL(u.block, 1) = 0, \'Activo\', \'Inactivo\') AS usu_estado', 'COUNT(b.ctf_id) AS nroCertificados'))
->from($db->quoteName('database_2.cargacliente', 'c'))
->join('INNER', $db->quoteName('database_2.cargas','a') . ' ON (' . $db->quoteName('a.crg_id') . ' = ' . $db->quoteName('c.cargas_id') . ') AND (' . $db->quoteName('a.crg_status') . ' = \'Ok\')')
->join('INNER', $db->quoteName('database_2.certificados','b') . ' ON (' . $db->quoteName('b.ctf_sede') . ' = ' . $db->quoteName('c.SEDE') . ') AND (' . $db->quoteName('b.ctf_nit') . ' = c.NIT)')
->join('LEFT', $db->quoteName('joomla_database.bml_users', 'u') . ' ON (' . $db->quoteName('c.user_id') . ' = ' . $db->quoteName('u.id') . ')')
->group(array('c.NIT', 'c.SEDE'))
->order(array('usu_razonSocial', 'usu_nit', 'usu_sede'));
This is a bit difficult to say what the problem is without having the right environment.
I would suggest to debug through the driver to see where it fails.
You can of course also put the query direct through the "setQuery" method. It would be however compatible with MySQL only.
But, once again, please update your Joomla! to the latest version ASAP.
I can't get the JOIN syntax correct to alter this existing MySQL query in PHP to include a join from another table. I have another table specified as DB_TABLE2 that contains columns InvmNumr and InvmDesc. The InvmNumr and InvlNumr are the exact same value in each table and I need to display InvmDesc from Table 2 in this query?
$res = mysql_query('SELECT LocId, InvlNumr, InvlQuant FROM ' . DB_TABLE1
. ' WHERE LocId = \'' . mysql_real_escape_string($cType) . '\'
AND InvlNumr = \'' . mysql_real_escape_string($br) . "'");
$markup = '';
Read up on LEFT JOIN vs INNER JOIN depending on how your data is stored in your DB_TABLE2 table.
$res = mysql_query('SELECT ' . DB_TABLE1 . '.LocId, ' . DB_TABLE1 . '.InvlNumr, ' .
DB_TABLE1 . '.InvlQuant, ' . DB_TABLE2 . '.InvmDesc
FROM ' . DB_TABLE1 . ' LEFT JOIN ' . DB_TABLE2 . ' ON ' .
DB_TABLE1 . '.InvlNumr = ' . DB_TABLE2 . '.InvmNumr
WHERE ' . DB_TABLE1 . '.LocId = \'' . mysql_real_escape_string($cType) . '\'
AND ' . DB_TABLE1 . '.InvlNumr = \'' . mysql_real_escape_string($br) . "'");
try this
SELECT db1.LocId,db1.InvlNumr,db1.InvlQuant
FROM DB_TABLE1 db1
INNER JOIN DB_TABLE2 db2 ON db1.InvlNumr = db2.InvlNumr
WHERE dbq.LocId = $cType
AND db1.InvlNumr = $br