issue in mysql query in codeigniter only if I add if condition - mysql

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

Whats wrong with my query, should i use WHERE?

So, what am i doing wrong?
This query:
$query = "INSERT INTO table1 (art_nr, article, balance, list_type)
VALUES('$art_nr', '$article', '$balance', '$list_type')
ON DUPLICATE KEY UPDATE balance = sum(balance + '$quantity_ordered');
UPDATE table2 SET list = 'History' WHERE id = '$id'";
Will give me this error:
Failed to run query: SQLSTATE[HY000]: General error: 1111 Invalid use
of group function
This query:
$query = "INSERT INTO table1 (art_nr, article, balance, list_type) VALUES('$art_nr', '$article', '$balance', '$list_type')
ON DUPLICATE KEY UPDATE balance = sum(balance + '$quantity_ordered') WHERE art_nr = '$art_nr';
UPDATE table2 SET list = 'History' WHERE id = '$id'";
Will give me this error:
Failed to run query: 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 'WHERE art_nr = 'S2Bygel'; UPDATE purchase_orderlist SET
list' at line 2
UPDATE
This was my first query. With Params:
//SECURITY
$params_array= array(
':id' => $_POST['formData']['id'],
':art_nr' => $_POST['formData']['art_nr'],
':article' => $_POST['formData']['article'],
':quantity_ordered' => $_POST['formData']['quantity_ordered'],
':list_type' => $_POST['formData']['list_type']
);
//QUERY
$query = "INSERT INTO table1 (art_nr, article, balance, list_type) VALUES (:art_nr, :article, :balance, :list_type)
ON DUPLICATE KEY UPDATE balance = balance + VALUES(:quantity_ordered) WHERE art_nr = :art_nr;
UPDATE table2 SET list = 'History' WHERE id = :id";
The problem with this query is that im running two querys at the same time. and then i will get this error:
Failed to run query: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
SUCCESS
I had to use prepared statements and separate my two querys:
//SECURITY
$params_array= array(
':art_nr' => $_POST['formData']['art_nr'],
':article' => $_POST['formData']['article'],
':quantity_ordered' => $_POST['formData']['quantity_ordered'],
':list_type' => $_POST['formData']['list_type']
);
//QUERY
$query = "INSERT INTO table1
(art_nr, article, balance, list_type)
VALUES (:art_nr, :article, :quantity_ordered, :list_type)
ON DUPLICATE KEY UPDATE
art_nr = art_nr, article = article, balance = balance + :quantity_ordered, list_type = list_type";
//EXECUTE
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($params_array);
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
//SECURITY
$params_array= array(
':id' => $_POST['formData']['id']
);
//QUERY
$query = "UPDATE table2 SET list = 'History' WHERE id = :id";
//EXECUTE
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($params_array);
echo "success";
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
You just want to add the value of $quantity_ordered to balance for the row? Then you don't need the sum() aggregation function. Just the + operator is enough.
But it seems like you're doing this in a host language like PHP. You should urgently learn to use parameterized queries! Do not use string concatenation (or interpolation) to get values in a query. That's error prone and may allow SQL injection attacks against your application.

mysql query error when have '(' but no ')'

$q = "select * from product where decription = ?";
$param = 'package ( 2 chicken wings, 3 salad';
$result = DB::select($q, array($param));
there is an error query because the param string don't have ')'..
how to prevent query if there is '(' but no ')' in string?
error message : Syntax error or access violation: 1064 syntax error, unexpected $end
Look, you dont have $query.. that would be $q not $query
The answer is $result = DB::select($q, array($param));

Query Failed: You have an error in your SQL syntax

Database query failed: 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 'LIMIT 1' at line 1
function get_subject_by_id($subject_id) {
global $connection;
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE id=" . $subject_id ." ";
$query .= "LIMIT 1";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
// REMEMBER:
// if no rows are returned, fetch_array will return false
if ($subject = mysql_fetch_array($result_set)) {
return $subject;
} else {
return NULL;
}
}
?>
Try to replace all the query thing by this:
$query = "
SELECT *
FROM subjects
WHERE id = $subject_id
LIMIT 1";
I'd be looking at what your passing into $subject_id.
Please please please don't use SELECT *. Even if you want all of the columns, write them out. If your tables change and get more columns added then your pulling along more data.

wordpress plugin sql synatax

problem in Mashable Slider Clone plugin when uload it in server
WordPress database 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 ')' at line 3] SELECT * FROM wp_mash_fields WHERE docid IN()
code for this is
$sql = "SELECT *
FROM $this->flds
WHERE docid IN(".implode(',' , array_keys($r)).")";
$r2 = $this->db->get_results($sql, ARRAY_A);
WordPress database 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 'LIMIT 0,999' at line 3] SELECT SQL_CALC_FOUND_ROWS DISTINCT wp_mash_documents.* FROM wp_mash_documents WHERE wp_mash_documents.type='image' ORDER BY wp_mash_documents. LIMIT 0,999;
code for this is
function get($type, $page = 0, $limit = 10, $sort = 'modify_time', $ord = 'ASC', $rel = null, $dorder = false, $s = null)
{
$ll = $page * $limit;
$docs = $this->docs;
$flds = $this->flds;
$rels = $this->rels;
$inner = array();
$where = array();
$order = '';
// get ids
$sql = "SELECT SQL_CALC_FOUND_ROWS DISTINCT $docs.*".($dorder? ",$rels.dorder" : "")." FROM $docs";
switch ($sort) {
case "title":
$inner[$flds] = array("$docs.id", "$flds.docid");
$where["$flds.name"] = "='title'";
$order = "$flds.value_text $ord";
if (isset($s)) {
$where["MATCH ($flds.value_text)"] = " AGAINST ('$s')";
}
Given your error message:
ORDER BY wp_mash_documents. LIMIT 0,999;
^---missing field name

Question mark DQL is not considered?

I have the following DQL query:
$query = Doctrine_Query::create()
->select('p.genre')
->from('Profile p')
->where('sf_guard_user_id = ?', 11);
If I return the SQL syntax with $sql = $query->getSqlQuery(); I get:
SELECT p.id AS p__id, p.genre AS p__genre FROM profile p WHERE (p.sf_guard_user_id = ?)
This is not normal. It should be 11 not ?:
SELECT p.id AS p__id, p.genre AS p__genre FROM profile p WHERE (p.sf_guard_user_id = 11)
And if I write:
$query = Doctrine_Query::create()
->select('p.genre')
->from('Profile p')
->where('sf_guard_user_id = ' . 11);
The SQL syntax is correct.
Normally DQL should do this automatically. Why isn't happening ?
This is how prepared statement works. Values will be bound on database server Hence doctrine can not show the real values with the query.
Doctrine will show a question mark if you use prepared statement not the real value.
Checkout how it is describing here