Codeigniter sql syntax error? - php

Because I codeigniter returns a syntax error?
$handler_feedback = $this->CI->db
->select('
feedback.id as feedback_id,
feedback.titulo,
relacion_feedback_usuario_principal.valor
')
->from('feedback')
->join(
'relacion_feedback_usuario_principal',
'
relacion_feedback_usuario_principal.feedback_id = feedback.id AND
relacion_feedback_usuario_principal.usuario_principal_id = 20
',
'left'
)
->get();
Error Number: 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 '' at line 3
SELECT `feedback`.`id` as feedback_id, `feedback`.`titulo`, `relacion_feedback_usuario_principal`.`valor` FROM (`feedback`) LEFT JOIN `relacion_feedback_usuario_principal` ON `relacion_feedback_usuario_principal`.`feedback_id` = `feedback`.`id` AND
Filename: /dir/file.php
Line Number: 289
Mi original query:
SELECT
feedback.id as feedback_id,
feedback.titulo,
relacion_feedback_usuario_principal.valor
FROM feedback
LEFT JOIN relacion_feedback_usuario_principal ON (
relacion_feedback_usuario_principal.feedback_id = feedback.id AND
relacion_feedback_usuario_principal.usuario_principal_id = 20
)

It should work the way you have written it.
Its as simple as,
$this->db->join('B', 'aCol = bCol AND bOtherCol = 0');
$this->db->get('A');
Anyways can you try the other way (join with a where clause),
$this->db->select('t1.id as feedback_id, t1.titulo, t2.valor');
$this->db->from('feedback as t1');
$this->db->join('relacion_feedback_usuario_principal as t2', 't1.id = t2.feedback_id', 'left');
$this->db->where('t2.usuario_principal_id', 20);
$query = $this->db->get();

relacion_feedback_usuario_principal.feedback_id = feedback.id AND
relacion_feedback_usuario_principal.usuario_principal_id = 20
Do you have a space between AND and relaction_feedback_ususario_principal.usuario_principal_id=20?

I have come to conslusion my code is not bad, it's a bug in codeigniter.

Related

facing query generation issue while datatable ajax processing [duplicate]

In below code, whenever I am adding below code with if conditions, i am getting error
if($this->ion_auth->is_customer())
$this->db->where('company_database.cdb_customer_id',$this->session->userdata('user_id'));
$this->db->select('company.*, cities.name as company_city, states.name as company_state, countries.name as company_country');
$this->db->from('company as company');
$this->db->join(CITIES.' as cities','cities.id = company.company_city_id' ,'left');
$this->db->join(STATES.' as states','states.id = company.company_state_id' ,'left');
$this->db->join(COUNTRIES.' as countries','countries.id = company.company_country_id' ,'left');
$this->db->join(COMPANY_DATABASE.' as company_database','company_database.cdb_company_id = company.company_id' ,'left');
if($this->ion_auth->is_customer())
$this->db->where('company_database.cdb_customer_id',$this->session->userdata('user_id'));
$this->db->where('company.company_delete_status',NOT_DELETED);
$query = $this->db->get();
echo '<pre>';
echo $this->db->get_compiled_query();
print_r($query->result());
echo $this->db->last_query();
What is the issue above query ?
I am getting below issue related to query
Error Number: 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 'WHERE `company_database`.`cdb_customer_id` = '19' AND `company`.`company_delete_' at line 2
SELECT * WHERE `company_database`.`cdb_customer_id` = '19' AND `company`.`company_delete_status` = 0
Filename: controllers/Test.php
Line Number: 112
You don't have a "from" clause in your where clause.
select * {from company} where 'company_database'.'cdb_customer_id' = ....
I suspect that the function
$this->ion_auth->is_customer()
may be calling another DB query and that pretty much completes the query you started above and once completed it does the $this->db with just the where clauses after.
To fix call the $this->ion_auth->is_customer() before you do $this->db->select and then in the IF statement simply just use the boolean returned so you don't
make another call to a query while you form another query.
Example:
--ADD THIS LINE
$bIsClient = $this->ion_auth->is_customer();
$this->db->select('company.*, cities.name as company_city, states.name as company_state, countries.name as company_country');
$this->db->from('company as company');
$this->db->join(CITIES.' as cities','cities.id = company.company_city_id' ,'left');
$this->db->join(STATES.' as states','states.id = company.company_state_id' ,'left');
$this->db->join(COUNTRIES.' as countries','countries.id = company.company_country_id' ,'left');
$this->db->join(COMPANY_DATABASE.' as company_database','company_database.cdb_company_id = company.company_id' ,'left');
--AND CHANGE THIS
if($bIsClient)
$this->db->where('company_database.cdb_customer_id',$this->session->userdata('user_id'));
$this->db->where('company.company_delete_status',NOT_DELETED);
$query = $this->db->get();
echo '<pre>';
echo $this->db->get_compiled_query();
print_r($query->result());
echo $this->db->last_query();

PHP throws error when showing SQL Server query that works in SSMS

This query works perfect when executed in SQL Managament Studio:
SELECT [UID], Plant, [Truck_n°], AlplaSTOCKBOL, Article, LoadingDate, CONVERT(VARCHAR(10), LoadingDate, 103) as 'LoadingDay', CONVERT(VARCHAR(5), LoadingDate, 14) as 'LoadingTime', Real_Status, New_DH, Comments,
CASE
WHEN ((AlplaSTOCKBOL IS NULL OR AlplaSTOCKBOL = '') and LoadingDate < GETDATE() and coalesce(Real_Status, 'NULL') != 'Cancelado') THEN 'C'
ELSE 'NC'
END AS 'ColorBOL'
FROM (
SELECT CONCAT(LA.IdLadeAuftrag, K.IdArtikelVarianten) as 'UID', 'FRBLO1' as 'Plant', LA.IdLadeAuftrag AS 'Truck_n°', LA.LadeDatum AS 'LoadingDate', LA.IdSpediteur AS 'IDTransport', LA.SpediteurBez AS 'TruckCompany', LA.Typ AS 'Type', A.LieferDatum AS 'Deliverydate', AV.Alias AS 'Article', (SELECT MAX(J.JournalNummer) FROM [AlplaPROD_eslef1].[dbo].T_EAIJournal AS J WHERE (J.IdJournalTyp = '6' OR J.IdJournalTyp = '4' OR J.IdJournalTyp = '3') AND J.IdLadeAuftrag = LA.IdLadeAuftrag) AS 'AlplaSTOCKBOL'
FROM [AlplaPROD_eslef1].[dbo].V_LadeAuftraege AS LA INNER JOIN
[AlplaPROD_eslef1].[dbo].V_LadePlanungen AS LP ON LA.IdLadeAuftrag = LP.IdLadeAuftrag INNER JOIN
[AlplaPROD_eslef1].[dbo].V_Konten AS K ON LP.IdKonto = K.IdKonto INNER JOIN
[AlplaPROD_eslef1].[dbo].V_Artikelvarianten_BASIS AS AV ON K.IdArtikelVarianten = AV.IdArtikelvarianten INNER JOIN
[AlplaPROD_eslef1].[dbo].V_Abrufe AS A ON LP.IdAbrufe = A.IdAbrufe
WHERE LA.LadeDatum between DATEADD(HOUR, -24, GETDATE()) and DATEADD(HOUR, 48, GETDATE()) AND LA.Status <>'31'
GROUP BY LA.IdLadeAuftrag, LA.LadeDatum, LA.IdSpediteur, LA.SpediteurBez, LA.Typ, A.LieferDatum, AV.Alias, LA.Bemerkung, K.IdArtikelVarianten
) SV
LEFT JOIN [AlplaPROD_eslef1_cus].[dbo].truckviewer_eslef1_outgoing on SV.[UID] = ID
ORDER BY LoadingDate ASC
But for some reason, when executed with a PHP Code, it throws the error
sqlsrv_fetch_array() expects parameter 1 to be resource, bool given....
If I try a simpler query, like
select TOP 50 * from IdLadeAuftrag
it also works perfect, so it is not a connection issue.
The only thing that COULD cause problems is because I get data from two different databases, but both are on the same server, and the user also has access to both.
This is the connection string used:
<?php
$serverName = "server_name";
$connectionInfo = array("Database"=>"database","UID"=>"user","PWD"=>"password");
$conn = sqlsrv_connect($serverName, $connectionInfo);
?>
If needed, the PHP code to show the query is:
$resultset = sqlsrv_query($conn, $sql); # $sql is the query written above
while( $rows = sqlsrv_fetch_array( $resultset, SQLSRV_FETCH_ASSOC ) ) {
## Table written here ##
}
Tried everything, even recreating the query with some changes, but I always get the same error.
Would appreciate some insight to find the issue.
With SQL_ERRORS() I get this information:
SQLSTATE: 42000
code: 156
message: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near the keyword 'CONVERT'.
SQLSTATE: 42000
code: 102
message: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near 'K'.
SQLSTATE: 42000
code: 156
message: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near the keyword 'AS'.

MariaDB / CodeIgniter / PHPColors

Can somebody help me with this error.
The PHP below
public function color_sql($filter)
{
$this->db->select('*, sum(count) AS color_sum');
$this->db->from('wallpapers_colors');
$this->db->where('saturation BETWEEN ' . (($filter['saturation'][0]) / 100) . ' AND ' . (($filter['saturation'][1]) / 100));
$this->db->where('lightness BETWEEN ' . (($filter['lightness'][0]) / 100) . ' AND ' . (($filter['lightness'][1]) / 100));
$this->db->where('hue BETWEEN ' . ($filter['hue'][0]) . ' AND ' . ($filter['hue'][1]));
$this->db->group_by('wallpaper_seq_id');
return $this->sql();
}
returns the below error
A Database Error Occurred
Error Number: 1064
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 'BETWEEN0 AND 0.4 AND `lightness` BETWEEN 0.08 AND 0.48 AND `hue` BETWEEN0 AND 20' at line 4
SELECT COUNT(*) AS `numrows` FROM ((SELECT *, sum(count) AS color_sum FROM `WS_wallpapers_colors` WHERE `saturation` BETWEEN0 AND 0.4 AND `lightness` BETWEEN 0.08 AND 0.48 AND `hue` BETWEEN0 AND 20 GROUP BY `wallpaper_seq_id`) wc) JOIN `WS_wallpapers` `w` ON `w`.`wallpaper_seq_id` = `wc`.`wallpaper_seq_id` LEFT JOIN (SELECT `t2`.*, GROUP_CONCAT(c.category_slug order by c1.lvl desc SEPARATOR '/') AS cFullSlug, GROUP_CONCAT(c.category_name order by c1.lvl desc SEPARATOR '|') AS cFullName FROM `WS_closures` `c1` LEFT JOIN `WS_category` `c` ON `c`.`category_seq_id` = `c1`.`ancestor` LEFT JOIN `WS_category` `t2` ON `t2`.`category_seq_id` = `c1`.`descendant` GROUP BY `c1`.`descendant`) as c ON `c`.`category_seq_id` = `w`.`category_seq_id` WHERE `w`.`wallpaper_status` = 1 AND `w`.`wallpaper_approved` = 1
Filename: core/WS_Model.php
Line Number: 76
core/WS_Model.php
public function count() {
$this->eachDay_newCache();
$this->ShutDownCache();
$return = $this->db->count_all_results(); // this is line 76 from WS_Model.php
$this->turnOnCache();
return $return;
}
Anyone have any solution how to solve this error?
(As you can see there is a space in the PHP code after the "BETWEEN" word and I don't know why MariaDB seen without a space.)
Thank you!
Your Error message ( in part ) says
SELECT COUNT(*) AS `numrows` FROM
and in your SQL it says
$this->db->select('*, sum(count) AS color_sum');
They are two different things
So what is the actual code you have at line 76 in core/WS_Model.php because the error code is not coming from the SQL you have shown us.

Error Number: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax

I am getting below mysql database error
Error Number: 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 'option, GROUP_CONCAT(DISTINCT year_question_map.year) AS years, GROUP_CONCAT(DIS' at line 1
SELECT `questions`.*, `question_level`.*, `question_answer`.*, GROUP_CONCAT(DISTINCT question_option.question_option SEPARATOR '__') AS option, GROUP_CONCAT(DISTINCT year_question_map.year) AS years, GROUP_CONCAT(DISTINCT exams.exam_name) AS exams FROM `questions` LEFT JOIN `question_option` ON `question_option`.`question_id` = `questions`.`qid` LEFT JOIN `question_level` ON `question_level`.`level_id` = `questions`.`level_id` LEFT JOIN `question_answer` ON `question_answer`.`question_id` = `questions`.`qid` LEFT JOIN `year_question_map` ON `year_question_map`.`question_id` = `questions`.`qid` LEFT JOIN `exams` ON `exams`.`exam_id` = `year_question_map`.`exam_id` WHERE `questions`.`topic_id` = '1' GROUP BY `questions`.`qid` ORDER BY `qid` ASC
I am Using Codeigniter and here is my sql query in my model
$this->db->select("questions.*,question_level.*,question_answer.*,GROUP_CONCAT(DISTINCT question_option.question_option SEPARATOR '__') AS option,GROUP_CONCAT(DISTINCT year_question_map.year) AS years,GROUP_CONCAT(DISTINCT exams.exam_name) AS exams");
$this->db->from('questions');
$this->db->join('question_option','question_option.question_id = questions.qid','left');
$this->db->join('question_level','question_level.level_id = questions.level_id','left');
$this->db->join('question_answer','question_answer.question_id = questions.qid','left');
$this->db->join('year_question_map','year_question_map.question_id = questions.qid','left');
$this->db->join('exams','exams.exam_id = year_question_map.exam_id','left');
$this->db->where('questions.topic_id',$topicID);
$this->db->group_by('questions.qid');
$this->db->order_by('qid','ASC');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return FALSE;
}
You are using MYSQL Reserve Word in your query:
GROUP_CONCAT(DISTINCT question_option.question_option SEPARATOR '__') AS OPTION,
Note that OPTION is a reserve word you must need to use backtick or change it with other name.
This should be:
GROUP_CONCAT(DISTINCT question_option.question_option SEPARATOR '__') AS `OPTION`,
For reference, you can check the list of Reserve words here:
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
(R) with any word in given below reference indicates this is a reserve word.

SQLSTATE[42000]: Syntax error or access violation: 1064(previous answer is not helping)

I'm trying to fix this query, but for some reason, it's throwing error.
What changes should I make ?
Code
$statement=$conn->prepare("SELECT p.productid AS productid,
p.productname AS productname,
t.itemid AS itemid,t.amount AS amount,
t.is_completed AS is_completed,
t.id AS recordid
FROM products p,temporder t
where p.productid=t.itemid AND is_completed = 0
LIMIT 0, 30 AND t.email = ?");
$statement->execute(array($_SESSION['email']));
$rows=$statement->rowCount();//get no. of rows
$statement->setFetchMode(PDO::FETCH_ASSOC);
Error :
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 'AND t.email =
'test#gmail.com'' at line 1
change this
where p.productid=t.itemid AND is_completed = 0 LIMIT 0, 30 AND t.email = ?
to
where p.productid=t.itemid AND is_completed = 0 AND t.email = ? LIMIT 0, 30

Categories