facing query generation issue while datatable ajax processing [duplicate] - php

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();

Related

Correct sql query in CodeIgniter is giving an error

When I am running a query from CodeIgniter, I am getting this error.
A Database Error Occurred
Error Number: 42000/263
[Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Must specify
table to select from.
SELECT *
Filename: D:/xampp/htdocs/4hifi/system/database/DB_driver.php
Which is confusing cause exactly the same query executed directly in SQL-Server is giving correct results.
I am using CodeIgniter 3.1.9 , I already tried to inject $username variable to query in different ways, all are giving the same error.
Here is the code:
$sql = "select date, g1.product_name, g2.order_amount, g1.price, g1.id, g1.order_id, g1.action from dbo.orders g1 inner join (select product_name, SUM( order_amount) as order_amount from dbo.orders where action=1 and confirmed!=1 group by product_name) g2 on g2.product_name = g1.product_name where g1.confirmed !=1 and g1.kontrahent = ? and action = 1";
$db2->query($sql, $username);
$result = $db2->get()->result_array();
return $result;
The $db2->query($sql, $username); line itself should return the required result.No need to do db->get() in case of raw queries.
why are you doing that in two steps. You should use something like this
$sql = "select date, g1.product_name, g2.order_amount, g1.price, g1.id, g1.order_id, g1.action from dbo.orders g1 inner join (select product_name, SUM( order_amount) as order_amount from dbo.orders where action=1 and confirmed!=1 group by product_name) g2 on g2.product_name = g1.product_name where g1.confirmed !=1 and g1.kontrahent = ? and action = 1";
$result = $sql->result_array();
return $result;

Select from table where clause from array from another table

I'm trying to insert a failsafe into a code to prevent them from going a step further, and I've been scratching my head for a while now. I am able to put something into an array, but I am not able to get the items from the array to match the second select query. I only get Array instead of the value from the item.
My first select query is this:
$datohenter3 = "select DATE_FORMAT(datotid, '%Y.%m.%d') AS dato from gramorapport34 group by dato order by dato asc";
$hentdatoer = $db->query($datohenter3);
$periodedatoer = array();
for ($x = 1; $x <= $db->affected_rows; $x++) {
$periodedatoer[] = $hentdatoer->fetch_assoc();
}
Then I want to match the values from this array with my next select query:
$rapportdatoer = "select fradato, tildato from gramorapportlogg WHERE fradato IN('".$periodedatoer."') OR tildato IN('".$periodedatoer."')";
$rapportdatoeksist = $db->query($rapportdatoer);
if ( !$rapporteksist ) die('Database Error: '.$db->error);
while($row = mysqli_fetch_array($rapportdatoeksist))
{
print_r($row);
}
The errors I am getting are:
Notice: Array to string conversion for the second select
Database 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 ' fradato IN('Array') OR tildato IN('Array')' at line 1
I'm not an expert in JOIN SELECT queries. This is using MariaDB 10.3.12 with PHP7.2
var_dump available at: https://www.lokalradio.no/rapport/gramo/datohenttest.php
Notice that $periodedatoer is an array of array. Each element inside has 1 key of dato (as you var_dump displays).
So use array-column to get the values and then implode as:
$rapportdato = implode("','", array_column($periodedatoer, "dato"));
Now you can use $rapportdato in your second query as:
$rapportdatoer = "select fradato, tildato from gramorapportlogg WHERE fradato IN('" . $rapportdato . "') OR tildato IN('" . $rapportdato . "')";

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.

Codeigniter sql syntax error?

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.

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;";

Categories