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...
Related
This query was supposed to return me four rows: which are four people with status 50 (which, in the application means "maternity leave"). But it returns only one.
On HeidiSQL the query doesn't even run because it displays a
syntax error on line 13:
(...)
corresponds to your MariaDB server version for the right syntax to use near 'a.id_regiao = '$id_regiao'
AND a.cod_status = 50
AND a.status' at line 13 */"
Here is the query. I'm slowly becoming familiar with sql statements and i did search a lot on SO before asking it:
//SELECTING PROJECT DATA
$query = "SELECT b.id_clt,b.nome AS nome_clt,
a.id_evento AS a_id_evento,a.data AS a_data,a.data_retorno AS a_data_retorno,
c.id_evento AS c_id_evento,c.data AS c_data,c.data_retorno AS c_data_retorno,
(SELECT nome FROM projeto WHERE id_projeto = a.id_projeto) AS nome_projeto,
(SELECT nome FROM curso WHERE id_curso = b.id_curso) AS nome_curso,
DATE_FORMAT(a.data,'%d/%m/%Y') AS a_data_br,
DATE_FORMAT(a.data_retorno,'%d/%m/%Y') AS a_data_retorno_br,
DATE_FORMAT(c.data,'%d/%m/%Y') AS c_data_br,
DATE_FORMAT(c.data_retorno,'%d/%m/%Y') AS c_data_retorno_br
FROM rh_eventos AS a
INNER JOIN rh_clt AS b ON (a.id_clt = b.id_clt AND a.cod_status = 50)
LEFT JOIN rh_eventos AS c ON (b.id_clt = c.id_clt AND c.cod_status = 54)
WHERE $cond_projeto a.id_regiao = '$id_regiao'
AND a.cod_status = 50
AND a.status = 1
AND NOW() BETWEEN a.data AND a.data_retorno
ORDER BY nome_projeto,b.nome;";
The problem is here in the query:
WHERE $cond_projeto a.id_regiao = '$id_regiao'
This inserts a variable (or maybe a full test?) without proper syntax. If it is a variable, include the table's column name in the criterium. If it is a full test, include AND like so:
WHERE $cond_projeto AND a.id_regiao = '$id_regiao'
Beware though! Use prepared statements, your code now appears to be vulnerable to SQL injection attacks (and those are not to be trifled with).
Here is the query, (as seen by using an echo before it) . I can see the output on heidsql now. Now its better for us to check it:
SELECT b.id_clt,b.nome AS nome_clt,
a.id_evento AS a_id_evento,a.data AS a_data,a.data_retorno AS a_data_retorno,
c.id_evento AS c_id_evento,c.data AS c_data,c.data_retorno AS c_data_retorno,
(SELECT nome FROM projeto WHERE id_projeto = a.id_projeto) AS nome_projeto,
(SELECT nome FROM curso WHERE id_curso = b.id_curso) AS nome_curso,
DATE_FORMAT(a.data,'%d/%m/%Y') AS a_data_br,
DATE_FORMAT(a.data_retorno,'%d/%m/%Y') AS a_data_retorno_br,
DATE_FORMAT(c.data,'%d/%m/%Y') AS c_data_br,
DATE_FORMAT(c.data_retorno,'%d/%m/%Y') AS c_data_retorno_br
FROM rh_eventos AS a
INNER JOIN rh_clt AS b ON (a.id_clt = b.id_clt AND a.cod_status = 50)
LEFT JOIN rh_eventos AS c ON (b.id_clt = c.id_clt AND c.cod_status = 54)
WHERE a.id_regiao = '1' AND a.cod_status = 50
AND a.status = 1
AND NOW() BETWEEN a.data AND a.data_retorno ORDER BY nome_projeto,b.nome;
I can now see the output on heidsql, though i still cant figure out why it doesent bring the other thre rows.
My code:
$sql = "SET #row_number = 0; SELECT (#row_number:=#row_number + 1) AS num, player, reinforcees, reinforcers FROM _KoT_villages WHERE o = '".$data[2]."' OR o = '".$data[4]."' ORDER BY CASE WHEN player = '".$user_class->id."' THEN 1 ELSE 2 END";
$result = mysql_query($sql) or die(mysql_error());
The error:
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'SELECT (#row_number:=#row_number + 1) AS num, player,
reinforcees, reinforcers F' at line 1
When I echo the SQL statement, I get the following: SET #row_number = 0; SELECT (#row_number:=#row_number + 1) AS num, player, reinforcees, reinforcers FROM _KoT_villages WHERE o = '1' OR o = '5' ORDER BY CASE WHEN player = '2' THEN 1 ELSE 2 END
When I run that echod statement through phpMyAdmin, it runs successfully, and gives me rows of results.
But why doesn't it work in a PHP statement? What's going on? How do I get PHP to do what SQL is doing?
And before anyone says I haven't tried to find the answer myself, if you Google "sql variable" php site:stackoverflow.com, every question I find is about accessing SQL results in PHP (i.e., loops) or inserting PHP variables in SQL, which is not what I need. I'm trying to insert an SQL variable into the SQL statement.
Also: I realize I should stop using MySQL, and am in the process of converting, but in order to quickly resolve a bug...I'm using MySQL.
mysql_query doesn't support multiple queries in one call. You would need to upgrade to mysqli or PDO to enable that. In the meantime though, you can implement what you want in a single query using a CROSS JOIN to initialise the row_number variable e.g.
$sql = "SELECT (#row_number:=#row_number + 1) AS num, player, reinforcees, reinforcers
FROM _KoT_villages
CROSS JOIN (SELECT #row_number := 0) r
WHERE o = '".$data[2]."' OR o = '".$data[4]."'
ORDER BY CASE WHEN player = '".$user_class->id."' THEN 1 ELSE 2 END";
The MySQL client in php expects individual statements
Open MySQL client
First Statement:
SET #row_number = 0
2nd Statement:
SELECT
(#row_number:=#row_number + 1) AS num,
player,
reinforcees,
reinforcers
FROM
_KoT_villages
WHERE
o = '".$data[2]."'
OR o = '".$data[4]."'
ORDER BY
CASE WHEN player = '".$user_class->id."' THEN 1
ELSE 2
END
$result = mysql_query( [2nd Statement] ) or die(mysql_error());
Close MySQL client
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
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;";
I have got a question. I have not done this before and am not sure if that is how it should be done.
I have a mySQL query which is working correctly. I use it in phpMyAdmin query editor whenever I want to do an update. However, I want to make life easier for a user by putting the query in a php script so the user can just click a link and the task is done.
I did the following:
$sql = " SET #error_limit = 10E-6;
UPDATE (
SELECT r.rmc_id, 'rmc_raw_data' src, r.rmc_time, r.rmc_date, r.latitude, r.longitude,
IF(s.server_id IS NULL, 'Mobile', 'Both') c FROM rmc_raw_data r
LEFT JOIN server_log_data s
ON r.rmc_time = s.server_rmc_time AND r.rmc_date = s.server_rmc_date AND ABS(r.latitude - s.server_latitude)/r.latitude < #error_limit AND ABS(r.longitude - s.server_longitude)/r.longitude < #error_limit
UNION
SELECT s.server_id, 'server_log_data' src, s.server_rmc_time, s.server_rmc_date, s.server_latitude, s.server_longitude, IF(r.rmc_id IS NULL, 'Server', 'Both') c FROM rmc_raw_data r
RIGHT JOIN server_log_data s
ON r.rmc_time = s.server_rmc_time AND r.rmc_date = s.server_rmc_date AND ABS(r.latitude - s.server_latitude)/r.latitude < #error_limit AND ABS(r.longitude - s.server_longitude)/r.longitude < #error_limit
) t
LEFT JOIN rmc_raw_data r1
ON r1.rmc_id = t.rmc_id AND t.src = 'rmc_raw_data'
LEFT JOIN server_log_data s1
ON s1.server_id = t.rmc_id AND t.src = 'server_log_data'
SET
r1.data_source = c, s1.data_source = c;";
$result = mysql_query($sql, $link);
if($result){
echo " Query executed successfully";
...
...
So I put the whole thing my php script but got a mysql error:
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 'UPDATE ( SELECT r.rmc_id, 'rmc_raw_data' src, r.rmc_time, r.rmc_date, r.latit' at line 1
Could someone suggest what am doing wrong here? It is my thinking that the error limit I have set on the first line of the query is responsible but I had thought that one could put his working query in the mysql_query() and it works.
'rmc_raw_data' src, this quotes will break the query ???