How to remove extra apostrophe - mysql

I wrote a SQL query to find the desired output for my project. I was working fine with the correct output. But suddenly it started to give error and in the SQL query, there is some additional apoatrophe in. How to resolve it?
I tried to add the query to $this->db->query(); but still no use.
public function getStudentConut($id) {
$this->db->select('students.id')
->from('students')
->join('bp','students.pbp = bp.id','left')
->where(condition 1)
->where(condition 2);
$query1 = $this->db->get_compiled_select();
$this->db->select('students.id')
->from('students')
->join('bp','students.dbp = bp.id','left')
->where(condition 1)
->where(condition 2);
$query2 = $this->db->get_compiled_select();
$this->db->select('COUNT(id) as stud_count')
->from('('.$query1." UNION ALL ".$query2.') X')
->group_by('X.id');
$results = $this->db->get();
return $results->num_rows();
}
It was giving correct count earlier. But without any new changes, it started to give the error.
Now I get 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 '.id`` WHERE ``bp.some_value`` IS NULL AND ``students.`schoo' at line 2
SELECT COUNT(id) as stud_count FROM (SELECT students.id`` FROM ``students`` LEFT JOIN ``bp`` ON ``students.pbp`` = ``bp.id`` WHERE ``bp..Some other condition.. UNION ALL SELECT students.idFROMstudentsLEFT JOINbpONstudents.dbp=bp.id..some other condition....) X GROUP BYX.id`

I think the issue (at least with the double `) is that CodeIgniter isn't very good with subqueries and such. Basically every time you get the compiled select statement it already has the escape identifiers and then you are putting it in the from statement at the end which will add additional escape identifiers on top of that.
`->from('('.$query1." UNION ALL ".$query2.') X')`
Unfortunately, unlike other methods like set, from doesn't have a 2nd parameter that allows you to set escaping to false (which is what I think you need).
I suggest trying this:
$this->db->_protect_identifiers = FALSE;
$this->db->select('COUNT(id) as stud_count')
->from('('.$query1." UNION ALL ".$query2.') X')
->group_by('X.id');
$results = $this->db->get();
$this->db->_protect_identifiers = TRUE;
and also look in to this: ->where(condition 2); which I'm pretty sure shouldn't compile due to lack of quotes. You probably don't want this escaped so you can do ->where('condition 2', '', false); as per: https://www.codeigniter.com/user_guide/database/query_builder.html#CI_DB_query_builder::where
When all else fails, just know that CodeIgniter has some limitations with "advanced" queries and that maybe you should write it out manually as a string utilizing $this->db->escape_str(...) for escaping user input vars, and $this->db->query(...) to run the SQL.

Related

Is it possible to insert sql query in php array value?

for($count = 0; $count < count($_POST["item_sub_category"]); $count++)
{
$data = array(
':item_sub_category_id'
=> SELECT r_name FROM Repair where r_id = $_POST["item_sub_category"][$count]
);
$query = "INSERT INTO Repairlog (description,visitID) VALUES (:item_sub_category_id,'1')";
$statement = $connect->prepare($query);
$statement->execute($data);
}
As far as concerns, your code won't work. The SQL query that you are passing as a parameter will simply be interpreted as a string.
You could avoid the need for a loop by taking advantage of the INSERT INTO ... SELECT ... syntax. The idea is to generate an IN clause that contains all values that are in the array, and then run a single query to insert all records at once.
Consider:
$in = str_repeat('?,', count($_POST["item_sub_category"]) - 1) . '?';
$query = "INSERT INTO Repairlog (description,visitID) SELECT r_name, 1 FROM Repair WHERE r_id IN ($in)";
$statement = $connect->prepare($query);
$statement->execute($_POST["item_sub_category"]);
Note: it is likely that visitID is an integer and not a string; if so, then it is better not to surround the value with single quotes (I removed them in the above code).
TLDR; No.
Your question can be re-framed as: Can I write SQL code in php. The answer is NO. You can write the SQL code within a String type variable (or parameter) in php.
This is a general rule for any programming language, you cannot have multiple languages within the same file, as the language parser will not be able understand which syntax is that.
In order to embed a different language in another language, you need some kind of separator that will define when the new language or special type will start and when it will end.

Codeigniter sql binding

How do I use Codeigniter SQL Binding if there are two target dates?
Is how I did it below correct?
public function getInvestmentForBorrowing($id, $Interest, $Currency, $Loantime, $target_date, $Risk_category)
{
$query = '
select CASE WHEN (a.amount_financed - a.amount_invested - a.amount_withdrawn) < a.amount_per_borrower
THEN round((a.amount_financed - a.amount_invested - a.amount_withdrawn), 2)
ELSE round((a.amount_per_borrower) , 2)
END AS investable_amount, a.*,
c.IBAN as Return_IBAN, c.BIC as Return_BIC,
i.average_rate
from investment a
inner join userinfo c
on a.Owner = c.Owner and
c.UPDATE_DT is null
inner join exchange_rates i
on a.Currency = i.currency_id and
? between i.effective_dt and i.expiration_dt
where a.ORIG_ID = ? and
a.Interest <= ? and
a.Currency = ? and
a.status = 2 and
a.Loantime >= ? and
a.Available >= ? and
a.Risk <= ? and
a.UPDATE_DT is null
having investable_amount > 0';
$query = $this->db->query($query, array($target_date, $id ,$Interest, $Currency, $Loantime ,$target_date ,$Risk_category));
$result = $query->result();
return $result;
}
Write now the question marks just represent the array so I added two $target_date to the array but not sure if thats the right way to do it.
It appears to be ok according to the codeigniter documentation but i say that without regard to your original SQL being correct or not.
Just make sure that the number of ? match the number of values you are providing and they are in the right order.
One way to sanity check it, apart from just running it, is to place the following command right after you perform the query:
echo $this->db->last_query();
And providing it known data, you can cheat and just hard code some dummy values for testing, take the generated SQL and throw that into something like phpmyadmin and run it the generated SQL against the Database and see if it works with the expected results.
Just a side note regarding your variable naming style. I see you are mixing cases i.e. things like $target_date (all lower case) and $Risk_category (First letter uppercase). Just be aware that on a linux based system case does matter and mixing like that can cause errors. It's a good idea to decide on one and stick with it.

Quering with Python Connector with variables

i am new in python and i have a simple issue that i cannot resolve.
I am in windows platform and unfortunately i cannot change this cause of work. I have to connect to many mysql tables and do sort of things with the extracted data. The code that i have:
conn = mysql.connector.Connect(host='<ip>',user='<user>',\
password='',database='<my database>')
c = conn.cursor()
c.execute ("select field from TABLE")
results = c.fetchall()
for row in results:
c.execute("select * from otherTable where nodo = %s",(str(row[0])))
if c.rowcount == 0:
doSomething()
else:
doOtherThing()
c.close()
when I run this with Python34 i got the error:
"you have an error in your sql synthax; check the manual that corresponds to your mysql server version for the right synthax to use near '%s' at line 1
thanks
you need to put single quotes around your %s like this: c.execute("select * from otherTable where nodo = '%s'",(str(row[0])))
you should also consider putting your query in a variable and then executing it like so:
query = ("select * from otherTable where nodo = '%s'",(str(row[0])))
c.execute(query)
This way helps prevents potential sql injection attacks and allows you to do a print(query) so you can debug the sql statement if you are getting errors.

CodeIgniter Active Record, basic update give error

I'm new to CodeIgniter and I get an error I cannot understand.
This is the code that give the error:
$data = array('adr' => $address);
$this->db->where('id', $id);
$this->db->update('domains', $data);
The error is:
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 '://www.example.com WHERE id = '10'' at line 1
This is the query:
UPDATE `domains` SET `adr` = http://www.example.com WHERE `id` = '10'
If I change this to
UPDATE `domains` SET `adr` = 'http://www.example.com' WHERE `id` = '10'
it works. Why is CodeIgniter creating this erroneous query?
Try escaping the single quotes in the $address variable before you call the update method.
Generally the CodeIgniter will automatically surround the value of $address with a single quote. I do not know why did you get this error message?
Curious, see if it works when you escape the string use $this->db->escape()
$data = array('adr' => $this->db->escape($address));
$this->db->where('id', $id);
$this->db->update('domains', $data);
I have the same problem and codeigniter do not add single qoutes to where clause.
When you enter integer value, sql do not give error but when you put string value (as a variable) to where clause, it gives error. But when you add single quotes to query and run it on phpmyadmin, it works.
So the solution is adding (string) statement to your variable: as in this (string)$id
I wrote before to add single quotes to variable as '$id', but this will not going to work (I'm new to codeigniter&php, thanks to commenter Mitchell McKenna, I checked out what I wrote before)

MySQL Zend Framework - SQLSTATE[42000]: Syntax error or access violation: 1064

I've read every response I could fine on SO before posting this question. Although similar, none addressed my particular problem (or I didn't recognize them doing so).
I have a table class that extends Zend_Db_Table_Abstract. In the model, I'm trying to return a single row using a join() method and based on the table ID like this:
$getCategoryResults = $this->select();
$getCategoryResults->setIntegrityCheck(false)
->from(array('c'=> 'categories', '*'))
->join(array('e' => 'events'),'c.events_idEvent = e.idEvent', array())
->where("e.idEvent = ?", $idEvent);
when I echo the sql object, I get this:
SELECT `c`.* FROM `categories` AS `c`
INNER JOIN `events` AS `e` ON c.events_idEvent = e.idEvent
WHERE (e.idEvent = '1')
Oddly enough, if I use this format,
->where("e.idEvent = $idEvent");
my output is "WHERE (e.idEvent = 1)". The value is not enclosed in ticks, but either seems to work for MySQL. When I run the query in phpMyAdmin, I get this:
idCategory type displayOrder description localStartTime events_idEvent
1 individual 1 5k Run / Walk 2010-02-18 23:59:59 12 team 2 5k Team Category 2010-02-18 23:59:591 1
which is what I expected to see. But when I run my app in a browser, I get this ugliness:
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 'SELECT c.* FROM categories AS c INNER JOIN events AS e ON c.events_id' at line 1
I've checked every resource that I can think of. Hopefully, the combined awesomeness of SO uber-experts will make this my last stop. :D
Check out the second part of the error statement. Most likely it is regarding an access violation if the mysql elsewhere.
For reasons unknown to me, the app believed my $pageResult variable wasn't set. I discovered this after adding an isset() to the code like this:
try {
$getCategoryResults = $this->select();
$getCategoryResults->setIntegrityCheck(false)
->from(array('c'=> 'categories', '*'))
->join(array('e' => 'events'),'c.events_idEvent = e.idEvent', array())
->where("e.idEvent = ?", $idEvent);
if (isset($pageResult)) {
$pageResult .= $getCategoryResults;
}
else {
$pageResult = $getCategoryResults;
}
} catch (Exception $e) {
echo ( "Could not find matching categories for event id = $idEvent");
}
Problem went away which, of course, revealed the next problem lurking behind it. :D