What is wrong with this SQL syntax in Laravel? - php

This query uses $hotel_id, and two date variables to get some data from database. But I keep receiving this error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax
This is a piece of bigger query used in another project, and works perfectly there. But has some problems in my project that I can't figure out.
The $from_Date and $to_Date variables are alright.
What is wrong with this MySQL statement?
$splitDate = explode('/', $start);
$from_Date = jalali_to_gregorian($splitDate[0], $splitDate[1], $splitDate[2], 1);
$splitDate = explode('/', $end);
$to_Date = jalali_to_gregorian($splitDate[0], $splitDate[1], $splitDate[2], 1);
$query = DB::statement('SELECT DISTINCT t.type_id pmrtypeid ,(CASE WHEN COUNT(t.type_id)-qb.cntrttypid IS Null THEN COUNT(t.type_id) ELSE COUNT(t.type_id)-qb.cntrttypid END)cnttypeid FROM type t JOIN room r
on r.type_id=t.type_id
LEFT JOIN (SELECT DISTINCT rt.type_id rttypid,COUNT(rt.type_id)cntrttypid FROM reserve_type rt
JOIN reserve re
ON re.reserve_id=rt.reserve_id
JOIN type ty
ON ty.type_id=rt.type_id
WHERE ((? BETWEEN re.from_date AND re.to_date) or (? BETWEEN re.from_date AND re.to_date)) AND ty.hotel_id=?
GROUP BY rt.type_id)qb
ON qb.rttypid=t.type_id
JOIN reserve_span rsn
ON rsn.hotel_id=t.hotel_id
WHERE r.hotel_id=? AND ((? BETWEEN rsn.from_date AND rsn.to_date) and (? BETWEEN rsn.from_date AND rsn.to_date)) and rsn.is_enable=1
GROUP BY t.type_id)pmr
on pmr.pmrtypeid=tps.type_id
join type_feture tf
on tps.type_id=tf.type_id' , [$from_Date,$to_Date,$hotel_id,$hotel_id,$from_Date,$to_Date] );
}

The problem came out to be an extra piece of the other code in mine:
)pmr
on pmr.pmrtypeid=tps.type_id
join type_feture tf
on tps.type_id=tf.type_id
The useless parentheses created an error. I also changed DB::statement() into DB::select() as suggested by #Erubiel.

Why are you using DB::statement() instead of DB::select()?
Also, DB::statement() does not take the binding values array parameter.
https://laracasts.com/discuss/channels/laravel/l5-bindings-is-not-working-with-dbstatement

Related

WHERE NOT IN AND WHERE error

I tried moving the WHERE clause many times but I'm still having an error. Am I doing the WHERE NOT IN AND WHERE clause wrong? The code is working perfectly fine until I added the WHERE ha_rooms.deleted != 1 clause. I also tried using deleted <> 1 but it still shows the same error
$query2 = $this->db->query("SELECT * FROM ha_rooms
WHERE ha_rooms.deleted != 1 JOIN ha_user_room_merged
WHERE ha_rooms.room_id NOT IN (SELECT ha_user_room_merged.room_id
FROM ha_user_room_merged WHERE ha_user_room_merged.deleted = 0)
group by ha_rooms.room_id");
The error is this
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 'JOIN ha_user_room_merged WHERE ha_rooms.room_id NOT IN (SELECT
ha_user_room_merg' at line 1
If I said frankly, your query is not done properly in anyway but it gives pretty much clear vision of what you are trying to do if you don't have any other logic behind that. So, I would like to suggest you to do google for SQL Syntax, Ordering, use of GROUP BY, WHERE sub-query etc. BTW below is the proper version of your query please check if it's useful for you
SELECT hr.*
FROM ha_rooms hr
JOIN ha_user_room_merged hurm On hurm.room_id = hr.room_id
WHERE hurm.deleted = 0
AND hr.deleted <> 1
Use below codeigniter query. in your join there is no ON
$all_ids = 0;
$this->db->select('group_concat(room_id) as ids');
$this->db->where('deleted', 0);
$ids = $this->db->get('ha_user_room_merged')->row_array();
if($ids) {
$all_ids = explode(',', $ids['ids']);
}
$this->db->where('hr.deleted !=', 1);
$this->db->where_not_in('hr.room_id', $all_ids);
$this->db->join('ha_user_room_merged hrm', 'hrm.room_id = hr.room_id');
$this->db->group_by('hr.room_id');
$this->db->get('ha_rooms hr')->result_array();
Please try..
select * from ha_rooms as a inner join ha_user_room_merged b on a.ha_rooms.id = b.room_id
where b.deleted <> 0
Output
ha_rooms.room_id ha_user_room_merged.room_id deleted
1 1 1
2 2 1
3 3 1
4 4 1
Thanks :)

bindParam is not completing the sql query

I'm new to PDO statements and so far I've managed to work with it, use prepared statements and many things, until today.
I have two querys, the first retrieve some data, store the results and then the second query uses that data to retrieve the final data. I'm working on a bad designed DB, that's why I have to do weird things.
The first query gets the year of start and the year of end of a sport league. Then, the year is passed to the second query to get data between those years (WHERE).
The problem is that bindParam seems to not work, it doesn't bind the parameter, shows a ?, and then the SQL throws the following exception:
Connection failed: SQLSTATE[42000]: Syntax error or access violation:
1064 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 ''0701' AND ?'0630' ORDER BY e.FECHA DESC' at line 5
The SQL:
$sqlQueryAuxiliar = "SELECT ano_inicio, ano_fin
FROM TEMPORADAS
ORDER BY ano_inicio DESC
LIMIT 1;";
$sqlQuery = "SELECT e.id, e.JORNADA, DATE_FORMAT(e.FECHA, '%Y-%m-%d'),
e.HORA, c1.nombre_temporada, c2.nombre_temporada
FROM ENCUENTROS AS e
JOIN CLUBS AS c1 ON (e.COD_EQUIL = c1.siglas)
JOIN CLUBS AS c2 ON (e.COD_EQUIV = c2.siglas)
WHERE e.FECHA BETWEEN :anoInicio'0701' AND :anoFinal'0630'
ORDER BY e.FECHA DESC;";
And this is the PHP code:
$this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmtAux = $this->_db->prepare($sqlQueryAuxiliar);
$stmtAux->execute();
$fetched = $stmtAux->fetchAll();
$stmtAux = null;
$stmt = $this->_db->prepare($sqlQuery);
$stmt->bindParam(':anoInicio', $fetched[0][0], PDO::PARAM_STR, 12);
$stmt->bindParam(':anoFinal', $fetched[0][1], PDO::PARAM_STR, 12);
$stmt->execute();
while ($row = $stmt->fetch()) {
$partidos[] = $row;
}
$stmt = null;
You cannot concatenate strings in your query this way. Change your query to
SELECT e.id, e.JORNADA, DATE_FORMAT(e.FECHA, '%Y-%m-%d'), e.HORA, c1.nombre_temporada, c2.nombre_temporada
FROM ENCUENTROS AS e
JOIN CLUBS AS c1 ON (e.COD_EQUIL = c1.siglas)
JOIN CLUBS AS c2 ON (e.COD_EQUIV = c2.siglas)
WHERE e.FECHA BETWEEN :anoInicio AND :anoFinal
ORDER BY e.FECHA DESC
and the bindParams to
$stmt->bindValue(':anoInicio', $fetched[0][0] . '0701', PDO::PARAM_STR);
$stmt->bindValue(':anoFinal', $fetched[0][1] . '0630', PDO::PARAM_STR);
Stands to reason, you're building invalid sql:
WHERE e.FECHA BETWEEN :anoInicio'0701' AND :anoFinal'0630'
would be built as basically
WHERE e.FETCHA BETWEEN foobar'0701' AND barbaz'0630'
which is a syntax error.
You probably want
WHERE e.FETCH BETWEEN concat(:anoInicio, '0701') AND concat(:anoFinal, '0630')
instead.
If you are using bound parameters you should not also be passing in a hard-coded value in your query..
"SELECT e.id, e.JORNADA, DATE_FORMAT(e.FECHA, '%Y-%m-%d'), e.HORA, c1.nombre_temporada, c2.nombre_temporada
FROM ENCUENTROS AS e
JOIN CLUBS AS c1 ON (e.COD_EQUIL = c1.siglas)
JOIN CLUBS AS c2 ON (e.COD_EQUIV = c2.siglas)
WHERE e.FECHA BETWEEN :anoInicio AND :anoFinal
ORDER BY e.FECHA DESC;";

MySQL query can't handle variables

I'm trying to query to my database, but for some reason the query is only working when I enter the parameters hard coded. If I use variables, the query refuses to work...
This is my query with hard coded parameters and works just fine:
$q_jobs = 'select distinct nid from node n, field_data_field_job_tags as tags
where (type= \'job\' and n.language = \'nl\' and tags.entity_id = n.nid
and tags.field_job_tags_value = \'Enterprise Asset Management\')
order by n.changed desc limit 7';
But when I use variables, the query refuses to work...
$q_jobs = 'select distinct nid from node n, field_data_field_job_tags as tags
where (type= \'job\' and n.language = :lang and tags.entity_id = n.nid
and tags.field_job_tags_value = :title)
order by n.changed desc limit 7';
$results_jobs = db_query($q_jobs, array(':lang' => $language->language,
':title' => $node->title));
Although it's a Drupal query, I assume it's just an error somewhere in my syntax?
I get this error:
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 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 '(type= 'job' and n.language = 'nl' and tags.entity_id =
n.nid and tags.field_job' at line 1: select distinct nid from {node} n,
field_data_field_job_tags as tagswhere (type= 'job' and n.language = :lang and
tags.entity_id = n.nid and tags.field_job_tags_value = :title)order by
n.changed desc limit 7; Array ( [:lang] => nl [:title] => Enterprise
Asset Management ) in rd_get_related_news_and_blogs()
You have a typo here: field_data_field_job_tags as tagswhere (type= - there should be a space between tags and where so the quoted part of Your SQL should be field_data_field_job_tags as tags where (type=.
Always read all of the mysql error message - the query it is failing with is always quoted thus You can easily find any typo or other mistake in Your query.
EDIT: cos You don't believe me, here is repeated query from the mysql error message:
select distinct nid from {node} n, field_data_field_job_tags as tagswhere (type= 'job' and n.language = :lang and tags.entity_id = n.nid and tags.field_job_tags_value = :title)order by n.changed desc limit 7;
Now see where You have a newline in Your query and where should be (and is not) a space within the query MySQL returned as failing.
Then put a space at the end of every line and see that the query is working...
I will help You, there should be space between tags and where and between \'Enterprise Asset Management\') and order by - but it is NOT. The only space is between n.nid and and tags.field_job_tags_value because of the tab space...

Doctrine 2 / MySQL: having trouble turning SQL left joins to DQL left joins

So, the goal of my SQL is to get Apartments and some information about them.
This is the SQL:
SELECT apartment.id, AVG(review.staff), COUNT(distinct review.id), city.name as city_name, state.state as state_name,
MIN(room.price_per_night)
FROM room
LEFT JOIN apartment ON room.apartment_id=apartment.id
LEFT JOIN review ON room.apartment_id=review.apartment_id
LEFT JOIN city ON apartment.city_id = city.id
LEFT JOIN state ON city.city_state_id = state.id
GROUP BY apartment.id;
which works.
But when I try to turn it to DQL, everything goes fine until I try to join the review table:
$qb = $em->createQueryBuilder('c');
$qb->select("MIN(r.price_per_night), rev.id")
->from("TechforgeApartmentBundle:Room", 'r')
->leftJoin('r.apartment', 'a')
->leftJoin('Review', 'rev', \Doctrine\ORM\Query\Expr\Join::WITH, 'r.apartment = rev.apartment')
->groupBy('a.id');
It always complains about Review not being identified before:
[Semantical Error] line 0, col 116 near 'rev WITH r.apartment': Error:
Identification Variable Review used in join path expression but was
not defined before.
I tried alot, and nothing seemed to help.
I'm pretty sure you can leave off the WITH condition, assuming Apartment and Review have a mapped association.
$qb->select('MIN(r.price_per_night), rev.id')
->from('TechforgeApartmentBundle:Room', 'r')
->leftJoin('r.apartment', 'a')
->leftJoin('a.review', 'rev')
->groupBy('a.id');
If for some reason you do need the WITH condition, the syntax looks like this:
->leftJoin('a.review', 'rev', 'WITH', 'a.id = rev.apartment_id')
I solved this by using raw sql queries:
$em = $this->getDoctrine()->getEntityManager();
$stmt = $em->getConnection()
->prepare("...
");
$stmt->execute();

Cumulative DQL with Doctrine

Im having a hard time working out a proper DQL to generate cumulative sum. I can do it in plain SQL but when it comes to DQL i cant get hold of it.
Here is how it looks in SQL:
SELECT s.name, p.date_short, p.nettobuy,
(select sum(pp.nettobuy) as sum from price pp where pp.stock_id = p.stock_id and p.broker_id = pp.broker_id and pp.date_short <= p.date_short) as cumulative_sum
FROM price p
left join stock s on p.stock_id = s.id
group by p.stock_id, p.date_short
order by p.stock_id, p.date_short
Thanks
Hey, I have check the documentation for Doctrine 1.2, and the way to create the query is (put attention on the alias):
$query = Doctrine_Query::create();
$query->addSelect('AVG(price) as price');
$query->addSelect('AVG(cost) as cost');
// as many addSelect() as you need
$query->from('my_table');
To output the SQL query created:
echo $query->getSqlQuery();
To execute the statement:
$product = $query->fetchOne();
And to access the retrieved data is:
echo $product->getPrice();
echo $product->getCost();
Read the rest of the documentation at Group By Clauses.
You just specify the sum in your select part of the DQL:
$query = Doctrine_Query::create()
->select('sum(amount)')
->from('some_table');
Check out this page in the Doctrine documentation for more info.

Categories