CodeIgniter Active Record, basic update give error - mysql

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)

Related

How to remove extra apostrophe

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.

How to give single quotes in SQL Query using yii frameowrk?

I'm trying to execute following SQL query using YII frameowrk
Query= select * from table where name='Bachelor''s degree'
By executing the above query I'm getting empty results. But I have content in tables.
From my perspective I think Yii framework not accepts query with single quotes in its contents.
So could you please suggest some other idea to resolve this issue ?
Thanks in advance.
Try query with parameter.
$name = "Bachelor's degree";
Yii::app()->db->createCommand()
->select()
->from('table_name')
->where('name = :name', array(':name' => "{$name}"))
->queryAll();
In YII way, bind your value to the statement.
$name = "Bachelor's degree";
$command=Yii::app()->db->createCommand();
$command->select('table_column1,table_column2,table_column3');
$command->from('table');
$command->where('name=:name', array(':name'=>$name));
echo $command->queryAll();

Unknown column in 'where clause

I've read almost every single thread around the net about the Unknown column 'dfsd' in 'where clause
the dfsd is the string that I entered through a html form using the post method..
the php file(where the forms data are being sent) just checks if the line above is an existing user name.
function authCheck($usr,$psw){
print $usr;
mysql_real_escape_string($usr);
$sql = "select usrNameMarket from marketusr where usrNameMarket=$usr";
$result = mysql_query($sql) or die(mysql_error());
$records=mysql_num_rows($result); //elenxw gia eggrafes
if($records){
$queryData=mysql_fetch_array($result);
if($queryData['usrNameMarket']==$usr){
$usrNameChk="ok";
}
else{
$usrNameChk=null;
}
}
else{
$usrNameChk=null;
}
rest of the file ....
I get the error from MySQL telling me the column doesn't exist (although the value has been passed correctly, that's why I used the print function just to double check it)...
I add the single quotes:
$sql = "select usrNameMarket from marketusr where usrNameMarket='$usr'";
Then I get a syntax error when mysql_query executes...
Then I tried
$sql = "select usrNameMarket from marketusr where usrNameMarket='".$usr."'";
Still I get the same syntax error.
I don't know what is wrong I've tried everything...
Is it possible that I get that error because of the database structure or scheme or the data type of that field(which is varchar)?
Use marketusr.usrNameMarket instead of just usrNameMarket
try with:
$sql = "select usrNameMarket from marketusr where usrNameMarket='$usr'";

PHP/MySQL - Best use and practice of escaping strings [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to prevent SQL Injection in PHP
What is the best way to escape strings when making a query?
mysql_real_escape_string() seems good but I do not exactly know how to use it in properly.
Does this code do the job properly?
<?php
/* Let's say that the user types "'#""#''"\{(})#&/\€ in a textfield */
$newStr = mysql_real_escape_string($str);
$query = "INSERT INTO table username VALUES ($str)";
mysql_query($query);
?>
EDIT:
Now I have this code:
$email = $_POST['email'];
$displayName = $_POST['displayName'];
$pass = $_POST['pass1'];
$email = mysqli_real_escape_string($link, $email);
$displayName = mysqli_real_escape_string($link, $displayName);
$pass = mysqli_real_escape_string($link, $pass);
$insert = "INSERT INTO profiles (email, displayName, password)
VALUES ('$email', '$displayName', md5('$pass'))";
mysqli_query($link, $insert)
or die(mysqli_error($link));
But I get this 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 1
If the user enters:
'**!"#!#^!"#!"*#!"#^''''
The best way is not to escape the string at all, but instead use a parameterized query, which does it for you behind the scenes.
Using mysql_real_escape_string like that will work, but you need to:
Add quotes around the value.
Use the result $newStr, not the original value $str.
Change the tablename to a name that isn't a reserved keyword.
Add parentheses around the column list.
Try this:
$query = "INSERT INTO yourtable (username) VALUES ('$newStr')";
I also suggest that you check the result of mysql_query($query) and if there is an error, you can examine the error message:
if (!mysql_query($query))
{
trigger_error(mysql_error());
}
You should also consider using one of the newer interfaces to MySQL. The old mysql_* functions are deprecated and should not be used in new code.

SQL query dosnt know variables

I am trying to query some tables in my database using a simple dropdown in which the name of the tables are listed. the query has only one record result showing the name and age of the youngest institute registered in the database!
$table = $_GET['table'];
$query = "select max('$table'.est_year) as 'establish_year' from '$table' ";
I need to send the name of the table as variable to the querier php file. no matter the method is GET or POST in both ways when I put the variable name in the query statement, it gives the 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 '.order) as 'last' from 'customers'' "
You are wrapping the table name in single quotes, which is not valid SQL (that's the syntax for strings, not table names). You should either not wrap the name at all or else wrap it in backticks (on the american keyboard layout, that's the key above TAB).
You should also not quote the alias established_year:
select max(`$table`.est_year) as establish_year from `$table`
Also, your code is vulnerable to SQL injection. Fix this immediately!
Update (sql injection defense):
In this case the most appropriate action would likely be to validate the table name against a whitelist:
if (!in_array($table, array('allowed_table_1', '...'))) {
die("Invalid table name");
}
single quote ('), in mysql, it represents string value.
SELECT *, 'table' FROM `table`;
Demo
So your query should be
$table = $_GET['table'];
$query = "select max($table.est_year) as 'establish_year' from $table ";
Also read old post, phpmyadmin sql apostrophe not working.
Also your code is vulnerable to SQL Injection. You can use something like this
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
    $str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$firstName = clean($_POST['firstName']);
$lastName = clean($_POST['lastName']);
.
.
.